.transpose()
The .transpose()
method reverses or permutes the axes of an ndarray
.
Syntax
numpy.transpose(axes)
Where 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 reverse the order of axes.
Unlike the built-in numpy.transpose()
function, the numpy.ndarray.transpose()
method can accept the axes as separate arguments, as well as in the form of a tuple (i.e., array.transpose(2,0,1)
is the same as array.transpose((2,0,1))
).
If possible, the ndarray
returned will be a view of the original ndarray
‘s data.
Example
The example below creates a ndarray
and then uses .transpose()
.
import numpy as npnd1 = np.array([[1,2,3],[4,5,6]])print(nd1)print(nd1.transpose())
This produces the following output:
[[1 2 3][4 5 6]][[1 4][2 5][3 6]]
In the above output, the original array is a 2x3 matrix, and the transposed array is a 3x2 matrix.
Codebyte example
This codebyte example demonstrates how to create and manipulate a multi-dimensional array in Python using NumPy’s .transpose()
function.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly90 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours