.transpose()

Anonymous contributor's avatar
Anonymous contributor
Published May 25, 2022Updated Oct 13, 2024
Contribute to Docs

The .transpose() function reverses or permutes the axes of an ndarray.

Syntax

numpy.transpose(array, axes)

Where array is the ndarray to transpose. axes is a tuple or list with as many entries as there are dimensions, listing the 0-based indices of each index in the new order in which they’ll appear in the permuted array. If axes is omitted, .transpose() will simply reverse the order of axes.

If possible, the ndarray returned will be a view of the original ndarray‘s data.

Example

The below example creates an ndarray and then uses .transpose() on it:

import numpy as np
nd1 = np.array([[1,2,3],[4,5,6]])
print(nd1)
print(np.transpose(nd1))

This produces the following output:

[[1 2 3]
[4 5 6]]
[[1 4]
[2 5]
[3 6]]

Codebyte Example

The axes argument allows control over the specific reordering of dimensions in a tensor. Run the below codebyte example to see how .transpose() can be used to rearrange the three dimensions of a 3D array:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python:NumPy on Codecademy