Transpose is a way of obtaining a new matrix whose columns are the rows of the original matrix and rows are the columns of the original matrix.
Numpy provides transpose()
function to achieve this operation. There are two different syntax of transpose()
function:
np.transpose(array) OR np.ndarray.transpose()
Here, array
parameter is a Numpy array.
It is just a matter of preference which syntax you want to use.
Note: Following tutorials are essential to improve your understanding of performing various matrix operations in NumPy:
Let's see how we can use transpose()
function with the help of a couple of examples:
import numpy as np a = np.array([[14, 84, 13, 24, 45], [75, 32, 99, 21, 46]]) print('Original array:\n', a) print('Transpose of array using ndarray.transpose():\n', a.transpose()) print('Transpose of array using np.transpose():\n', np.transpose(a))
Output
Original array: [[14 84 13 24 45] [75 32 99 21 46]] Transpose of array using ndarray.transpose(): [[14 75] [84 32] [13 99] [24 21] [45 46]] Transpose of array using np.transpose(): [[14 75] [84 32] [13 99] [24 21] [45 46]]
Note: transpose()
function works on 2-D array and does not work on 1-D array.
import numpy as np a = np.array([1, 2, 3, 4, 5]) print('Original array:', a) print('Transpose of array: ', a.transpose())
Output
Original array: [1 2 3 4 5] Transpose of array: [1 2 3 4 5]
As you can see above transpose()
function has no effect on one-dimensional array.