NumPy: numpy.swapaxes() function

numpy.swapaxes() function

The numpy.swapaxes() function is used to interchange two axes of an array. It takes two arguments: axis1 and axis2 which are the integers representing the axes to be swapped.

The function is useful in reordering the dimensions of a given array. For instance, in image processing, a color image is represented as a 3D array with the dimensions (height, width, channels). To convert this representation to (channels, height, width), we can use the numpy.swapaxes() function.


numpy.swapaxes(a, source, destination)
NumPy manipulation: swapaxes() function


Name Description Required /
a Input array. Required
axis1 First axis. Required
start Second axis. Required

Return value:

a_swapped [ndarray] For NumPy >= 1.10.0, if a is an ndarray, then a view of a is returned; otherwise a new array is created. For earlier NumPy versions a view of a is returned only if the order of the axes is changed, otherwise the input array is returned

Example: Transposing a 1D array using numpy.swapaxes()

>>> import numpy as np
>>> a = np.array([[2,3,4]])
>>> np.swapaxes(a,0,1)

In the above code the array 'a' is defined as a 1D array with the values [2, 3, 4]. Then, the np.swapaxes() function is used to swap the axes at positions 0 and 1. This has the effect of transposing the array, turning it from a row vector into a column vector.

Pictorial Presentation:

NumPy manipulation: swapaxes() function

Python - NumPy Code Editor:

Previous: rollaxis()
Next: ndarray.T()

Follow us on Facebook and Twitter for latest update.