Let’s learn how to transpose matrix in Numpy Python library.
Using a numpy transpose method
I’ll create 5 x 2 array and transpose it into a new one. You will see how easy is that with Numpy.
Numpy provides a dedicated function, transpose, specifically for this purpose.
import numpy as np my_array = np.arange(11, 21).reshape(5, 2) transposed_array = np.transpose(my_array) print(f"My array: \n {my_array}") print(f"Transposed array: \n {transposed_array}")
I created a 5 x 2 array with values from 11 to 20. You can see how values are transposed in the output shown.
The transpose function returns a new matrix that is the transpose of the original matrix. In the example above, the original matrix has five rows and two columns, but the transposed matrix has two rows and five columns.
How to transpose a matrix in NumPy using the swapaxes method?
Another way to transpose a matrix in NumPy is to use the swapaxes method. The swapaxes method takes two axes as parameters and returns a new matrix with the axes swapped.
The following code shows how to transpose a matrix using the swapaxes method:
import numpy as np my_array = np.arange(11, 21).reshape(5, 2) transposed_array = np.swapaxes(my_array, 0, 1) print(my_array) print(transposed_array)
As you can see, the swapaxes method has also transposed the original matrix, so that the rows and columns have been switched.
The swapaxes method is a more general method than the transpose method, because it can be used to transpose matrices with any number of dimensions. However, the transpose method is more efficient, because it is specifically designed for transposing matrices.