NumPy Tutorial NumPy Statistics NumPy References

NumPy - rollaxis() function



The NumPy rollaxis() function rolls the specified axis backwards, until it lies in a given position. The syntax for using this function is given below:

Syntax

numpy.rollaxis(a, axis, start=0)

Parameters

a Required. Specify the input array (ndarray).
axis Required. Specify the axis to be rolled. The positions of the other axes do not change relative to one another.
start Optional. When start <= axis, the axis is rolled back until it lies in this position. When start > axis, the axis is rolled until it lies before this position. The default, 0, results in a 'complete' roll.

Return Value

Returns a view of a.

Example:

In the example below, the rollaxis() function is used to roll axis backwards of a given array.

import numpy as np

#creating an array of shape (3,4,5,6)
arr = np.ones((3,4,5,6))
print(arr.shape)

#roll axis backward
print(np.rollaxis(arr, 3, 1).shape)
print(np.rollaxis(arr, 2).shape)
print(np.rollaxis(arr, 1, 4).shape)

The output of the above code will be:

(3, 4, 5, 6)
(3, 6, 4, 5)
(5, 3, 4, 6)
(3, 5, 6, 4)

Example:

Consider one more example to understand this function.

import numpy as np

#creating an array of shape (2,2,2)
arr = np.arange(8).reshape(2,2,2)
print("The original array:")
print(arr)

#roll axis backward
print("\nThe array after rollaxis():")
print(np.rollaxis(arr, 1, 2))

The output of the above code will be:

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

 [[4 5]
  [6 7]]]

The array after rollaxis():
[[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]

❮ NumPy - Array Manipulation