Numpy.transpose() method is “used to get the permute or reserve the dimension of the input array, meaning it converts the row elements into column elements and the column elements into row elements.”
Syntax
numpy.transpose(a, axes=None)
Parameters
- a: array_like: It is the Input array.
- axes: tuple or list of ints, optional: If specified, it must be the tuple or list, which contains the permutation of [0,1,.., N-1] where N is the number of axes of a. The i’th axis of the returned array will correspond to an axis numbered axes[i] of the input. If not specified, defaults to the range(a.ndim)[::-1], which reverses the order of the axes.
Return value
The np.transpose() method returns an array with its axes permuted. A view is returned whenever possible.
Example 1: How to Use np.transpose() Method
import numpy as np
data = np.arange(6).reshape((2, 3))
print("Original Array")
print(data)
tMat = np.transpose(data)
print("Transposed Array")
print(tMat)
Output
Original Array
[[0 1 2]
[3 4 5]]
Transposed Array
[[0 3]
[1 4]
[2 5]]
Example 2: Using the T attribute
In Python, you can get a transposed matrix of the original two-dimensional array (matrix) with the T attribute.
import numpy as np
arr2d = np.arange(6).reshape(2, 3)
print(arr2d)
print('\n')
print('After using T attribute: ')
arr2d_T = arr2d.T
print(arr2d_T)
Output
[[0 1 2]
[3 4 5]]
After using T attribute:
[[0 3]
[1 4]
[2 5]]
Example 3: Provide an ndarray
The transpose() is provided as a method of ndarray. Like T, the view is returned.
import numpy as np
arr2d = np.arange(6).reshape(2, 3)
print(arr2d)
print('\n')
print('After using transpose() function: ')
arr2d_T = arr2d.transpose()
print(arr2d_T)
Output
[[0 1 2]
[3 4 5]]
After using transpose() function:
[[0 3]
[1 4]
[2 5]]
You can see that we got the same output as above.
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.