NumPy Tutorial NumPy Statistics NumPy References

NumPy - swapaxes() function



The NumPy swapaxes() function is used to interchange two axes of an array.

Syntax

numpy.swapaxes(a, axis1, axis2)

Parameters

a Required. Specify the input array (array_like).
axis1 Required. Specify the first axis.
axis2 Required. Specify the second axis.

Return Value

If a is an ndarray, then a view of a is returned; otherwise a new array is created.

Example:

In the example below, swapaxes() function is used to interchange two axes of an array.

import numpy as np

x = np.array([[1,2,3]])
y = np.array([[[1,2,3]],
              [[4,5,6]]])

#print x
print("x =")
print(x)

#swap axis of x 
print("\nnp.swapaxes(x,0,1) =")
print(np.swapaxes(x,0,1))

#print y
print("\ny =")
print(y)

#swap axis of y 
print("\nnp.swapaxes(y,0,2) =")
print(np.swapaxes(y,0,2))

The output of the above code will be:

x =
[[1 2 3]]

np.swapaxes(x,0,1) =
[[1]
 [2]
 [3]]

y =
[[[1 2 3]]

 [[4 5 6]]]

np.swapaxes(y,0,2) =
[[[1 4]]

 [[2 5]]

 [[3 6]]]

❮ NumPy - Array Manipulation