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.
Of course Numpy offers dedicated function for that purpose.
import numpy as np my_array = np.arange(11, 21).reshape(5, 2) transposed_array = np.transpose(my_array) print(my_array) print(transposed_array)
I created 5 x 2 array with values 11 – 20. You can see how values got transposed in the picure above.
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.
Key Takeaways
To transpose a matrix in NumPy, you can use the transpose() method or the swapaxes() method.
The transpose() method is specifically designed for transposing matrices, and it is more efficient than the swapaxes() method.
The swapaxes() method is a more general method that can be used to transpose matrices with any number of dimensions.
FAQs
What is a matrix?
A matrix is a rectangular array of numbers. It can be used to represent a variety of data, such as the coefficients of a linear equation or the values of a function at different points.
What is transposing a matrix?
Transposing a matrix means swapping the rows and columns. For example, if a matrix has dimensions (5, 2), then the transposed matrix will have dimensions (2, 5).
What are the benefits of transposing matrices?
There are a few benefits to transposing matrices. First, it can make it easier to perform certain operations on the matrix, such as finding the determinant or the inverse. Second, it can make the matrix more compatible with other functions or libraries.