NumPy – swap axes

NumPy - swap axes

In this chapter, we will discuss about NumPy – swap axes. This function interchanges the two axes of an array. For NumPy versions after 1.10, a view of the swapped array is returned. The function takes the following parameters.

numpy.swapaxes(arr, axis1, axis2)

Where,

Sr.No.Parameter & Description
1arrInput array whose axes are to be swapped
2axis1An int corresponding to the first axis
3axis2An int corresponding to the second axis

Example Of NumPy swap axes

# It creates a 3 dimensional ndarray 
import numpy as np 
a = np.arange(8).reshape(2,2,2) 

print 'The original array:' 
print a 
print '\n'  
# now swap numbers between axis 0 (along depth) and axis 2 (along width) 

print 'The array after applying the swapaxes function:' 
print np.swapaxes(a, 2, 0)

Its output would be as follows −

The original array:
[[[0 1]
 [2 3]]

 [[4 5]
  [6 7]]]

The array after applying the swapaxes function:
[[[0 4]
 [2 6]]
 
 [[1 5]
  [3 7]]]

Next Topic – Click Here

This Post Has 2 Comments

Leave a Reply