transpose() / .T (NumPy)

Transposing flips a 2-D array over its diagonal, swapping its rows and columns so an (m, n) array becomes (n, m). The shortcut is the .T attribute, and it returns a view rather than copying the data.

NumPy

a.T turns rows into columns: the element at position (i, j) ends up at (j, i). This is constant in matrix math — you transpose to align dimensions for multiplication, or to switch between row-oriented and column-oriented layouts.

Because transpose just relabels how the existing buffer is read (it changes the strides), it is a view and costs almost nothing in time or memory. Modifying the transposed array writes back to the original. For arrays of more than two dimensions, np.transpose lets you specify any permutation of the axes.

On a 1-D array transpose does nothing visible — a vector has no second axis to swap — which surprises people expecting a column vector; use reshape or np.newaxis to add that axis.

Syntax

a.T  |  a.transpose()  |  np.transpose(a, axes)

Examples

Python

import numpy as np
a = np.array([[1, 2], [3, 4]])
print(a.T)

Output:

[[1 3]
 [2 4]]

Learn it in a lesson

See also

Back to the Dictionary