﻿ How to Get the Transpose of a Matrix in Python using Numpy ﻿ # How to Get the Transpose of a Matrix in Python using Numpy In this article, we show how to get the transpose of a matrix in Python using the numpy module.

The transpose of a matrix is a matrix in which the columns and rows interchange. The columns become the rows (and the rows become the columns).

Just so that you can see an example, an example is shown below. So you see how in the original matrix, in the first column, we have, 5 6 7. In the transpose of this matrix, this 5 6 7 becomes the first row.

In the original matrix, in the second column, we have , 8 3 4. In the transpose of this matrix, this 8 3 4 becomes the second row.

In the original matrix, in the third column, we have, 2 9 1. In the transpose of this matrix, this 2 9 1 becomes the third row.

Thus, from an original matrix to the transpose of the matrix, the columns and rows interchange.

We can obtain the transpose of a matrix using the numpy module.

Below we create the same matrix that is seen in the example above and then we obtain the transpose of the matrix (which should be the same as that seen above).

So let's now go over the code.

So the first thing we must do is import the numpy module. We do so with the line, import numpy as np. The reason we put, as np, is so that we don't have to reference numpy each time; we can just use np.

We then create a variable called matrix1 and set it equal to, np.matrix([[5,8,2],[6,3,9],[7,4,1]])

We then reference matrix1 and you can see that it produces the matrix that we pictured above.

It's a 3x3 matrix, 3 rows and 3 columns.

We then obtain the transpose of the matrix with the line, matrix1.T

The .T attribute obtains the transpose of a matrix.

You can see that the transpose of a matrix is the original matrix with the columns and rows interchanged.

And this is how we can get the transpose of a matrix in Python with the numpy module.

Related Resources

How to Randomly Select From or Shuffle a List in Python