Javatpoint Logo
Javatpoint Logo

numpy.transpose() in Python

The numpy.transpose() function is one of the most important functions in matrix multiplication. This function permutes or reserves the dimension of the given array and returns the modified array.

The numpy.transpose() function changes the row elements into column elements and the column elements into row elements. The output of this function is a modified array of the original one.

Syntax

Parameters

arr: array_like

It is an ndarray. It is the source array whose elements we want to transpose. This parameter is essential and plays a vital role in numpy.transpose() function.

axis: List of ints()

If we didn't specify the axis, then by default, it reverses the dimensions otherwise permute the axis according to the given values.

Return

This function returns a ndarray. The output array is the source array, with its axis permuted. A view is returned whenever possible.

Example 1: numpy.transpose()

Output:

array([[0, 1, 2],
       	[3, 4, 5]])
array([[0, 3],
       	[1, 4],
       	[2, 5]])

In the above code

  • We have imported numpy with alias name np.
  • We have created an array 'a' using np.arange() function and gave a shape using reshape() function.
  • We have declared the variable 'b' and assigned the returned value of np.transpose() function.
  • We have passed the array 'a' in the function.
  • Lastly, we tried to print the value of b.

In the output, the transposed array of the original array has been shown.

Example 2: numpy.transpose() with axis

Output:

array([[1, 2],
            [4, 5],
            [7, 8]])
array([[1, 4, 7],
       	[2, 5, 8]])

In the above code

  • We have imported numpy with alias name np.
  • We have created an array 'a' using np.array() function.
  • We have declared the variable 'b' and assigned the returned value of np.transpose() function.
  • We have passed the array 'a' and the axis in the function.
  • Lastly, we tried to print the value of b.

In the output, the transposed array of the original array has been shown.

Example 3: Reposition elements using numpy.transpose()

Output:

(32L, 64L, 12L, 123L)
(12L, 64L, 32L, 123L)
  • We have imported numpy with alias name np.
  • We have created an array 'a' using np.ones() function.
  • We have declared the variable 'b' and 'c' and assigned the returned value of np.transpose() function.
  • We have passed the array 'a' and the positions of the array elements in the function.
  • Lastly, we tried to print the value of b and c.

In the output, an array has been shown whose elements are located at the defined position in the array.


Next Topicnumpy.mean()




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA