What is the numpy.roll() Function in Python

Numpy.roll() method is “used to roll array elements along the specified axis.” If an element is being rolled first to the last position, it is rolled back to the first position.

Syntax

numpy.roll(array, shift, axis=None)

Parameters

  1. array: It is an Input array whose elements are to be rolled.
  2. shift: It is of int and tuple datatype. It depicts no. of times we need to shift array elements. If it is of tuple type, then the axis must be a tuple of the same size, and the corresponding number shifts each of the given axes. If an int data type is used, the same value is used for all given axes for rolling in the input array.
  3. axis: It depicts the Plane along which we wish to roll an array or shift its elements.

Return Value

It returns an array rolled with the same size as of input array.

Example 1: How to Use the numpy roll() method

import numpy as np

# creating a sample array with arange and reshape function
array = np.arange(12).reshape(3, 4)
print("Original array : \n", array)

# Rolling array; Shifting one place
print("\nRolling with 1 shift : \n", np.roll(array, 1))

# Rolling array; Shifting four places
print("\nRolling with 4 shift : \n", np.roll(array, 4))

# Rolling array; Shifting five places with 1th axis
print("\nRolling with 5 shift with 1 axis : \n", np.roll(array, 2, axis=1))

Output

Original array :
 [[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]

Rolling with 1 shift :
 [[11 0 1 2]
 [ 3 4 5 6]
 [ 7 8 9 10]]

Rolling with 4 shift :
 [[ 8 9 10 11]
 [ 0 1 2 3]
 [ 4 5 6 7]]

Rolling with 5 shift with 1 axis :
 [[ 2 3 0 1]
 [ 6 7 4 5]
 [10 11 8 9]]

Example 2: Rolling a 2D NumPy array along an axis

import numpy as np


def roll_array(array, shift, axis):
 """Rolls a 2D NumPy array along an axis.

 Args:
 array: The 2D NumPy array to roll.
 shift: The amount to shift the array.
 axis: The axis along which to roll the array.

 Returns:
 The rolled array.
 """

 rolled_array = np.roll(array, shift, axis)
 if axis == 0:
 rolled_array[:shift] = array[-shift:]
 elif axis == 1:
 rolled_array[:, :shift] = array[:, -shift:]
 return rolled_array


if __name__ == "__main__":
  array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  rolled_array = roll_array(array, 2, 0)
  print(rolled_array)

Output

[[4 5 6]
 [7 8 9]
 [1 2 3]]

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.