Swap rows and columns of a 2-D array.
Matrix operations
NumPy · Function
Reorders the axes of an array. Without axes it reverses their order; with a permutation, it applies the specified output-axis order.
np.transpose returns an array whose axes are reordered. With no axes argument it reverses every axis; with an explicit permutation, each output axis takes its data from the corresponding input axis.
numpy.transpose(a, axes=None)| Name | Type | Description |
|---|---|---|
a | array_like | Input array-like object whose axes will be reordered. |
axes | tuple or list of ints, optional | Optional tuple or list of integers specifying the output-axis permutation. |
An ndarray with the axes of a permuted.
import numpy as np
x = np.arange(24).reshape(2, 3, 4)
y = np.transpose(x, (1, 0, 2))
print(x.shape) # (2, 3, 4)
print(y.shape) # (3, 2, 4)
print(y[1, 0, 2]) # x[0, 1, 2]
Reorders the first two axes while preserving the third axis, changing the shape from (2, 3, 4) to (3, 2, 4).
Matrix operations
Tensor layout
Shape inspection
np.transpose reorders an array's axes and returns the resulting array. Without axes, it uses the reversed axis order, so an array with shape (2, 3, 4) becomes (4, 3, 2).
Follow-up: What does an explicit permutation mean? For axes=(1, 0, 2), output axis 0 corresponds to input axis 1, output axis 1 to input axis 0, and output axis 2 to input axis 2.
For a two-dimensional array, it performs the standard matrix transpose. For an n-dimensional array, the supplied axes sequence determines the output-axis order.
Follow-up: How would you move the last axis to the front? For an array with ndim=N, use axes=(N-1, 0, 1, ..., N-2).
The function accepts array-like input and returns an ndarray with its axes permuted. Negative axis indices may also be used when specifying the permutation.
Follow-up: What constraint still applies with negative indices? After normalization, the values must still represent a complete permutation of the array's axes.
numpy.ndarray.transposenumpy.ndarray.Tnumpy.moveaxisnumpy.swapaxes