How to transpose (inverse columns and rows) a matrix using numpy in python ?


Examples of how to transpose (inverse columns and rows) a matrix using numpy in python:

Matrix transpose

Let's consider the following matrix:

\begin{equation}
M = \left( \begin{array}{ccC}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9
\end{array}\right)
\end{equation}

then, the matrix transpose is:

\begin{equation}
M^T = \left( \begin{array}{ccC}
1 & 4 & 7 \\
2 & 5 & 8 \\
3 & 6 & 9
\end{array}\right)
\end{equation}

Transpose a matrix using numpy (method 1)

>>> import numpy as np
>>> M = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> M
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> M.T
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])

Transpose a matrix using numpy (method 2)

>>> np.transpose(M)
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])

References