Summary: in this tutorial, you’ll learn how to use the numpy transpose()
function to reverse the axes of an array.
Introduction to the numpy transpose() function
The numpy
function reverses the axes of an array. Here’s the syntax of the transpose()
function:transpose()
numpy.transpose(a, axes=None)
Code language: Python (python)
In this syntax:
- a is an input array. It can be a numpy array or any object that can be converted to a numpy array.
- axes is a tuple or a list that contains a permutation of [0,1,..,N-1] where N is the number of axes of the array a.
The transpose()
function returns the array a
with its axes permuted.
The transpose()
function is equivalent to:
ndarray.T
property method that returns an array transposed.ndarray.transpose(*axes)
method that returns an array transposed.
NumPy transpose() function examples
Let’s take some examples of using the transpose()
function.
1) Using transpose() function with 1-D array example
The following example uses the transpose()
function with 1-D array:
import numpy as np
a = np.array([1, 2, 3])
b = np.transpose(a)
print(b)
Code language: Python (python)
Output:
[1 2 3]
Code language: Python (python)
The transpose()
function has no effect on a 1-D array because a transposed vector is simply the same vector.
2) Using numpy transpose() function with 2-D array example
The following example uses the transpose()
function to transpose a 2-D array (or a matrix):
import numpy as np
a = np.array([
[1, 2, 3],
[4, 5, 6]
])
b = np.transpose(a)
print(b)
Code language: Python (python)
Output:
[[1 4]
[2 5]
[3 6]]
Code language: Python (python)
In this example, the transpose()
function transpose a (2,3) array. Basically, it swaps rows and columns of the array.
After the transposition, the first row of array a becomes the first column of the transposed array b, the second row of array a becomes the second column of the transposed array b.
Summary
- Use the
transpose()
to transpose an array.