numpy.roll() – The NumPy roll Python Function

Introduction to NumPy roll

The numpy.roll() function moves elements in an array along a given axis. Essentially, the items of the input array are shifted. It is rolled back to the initial position if an element is rolled first to the last position.

Syntax:

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

Parameters:

  • array: [array_like] Input array, whose elements we want to roll
  • shift: [int or int_tuple] No. of times we need to shift array elements. If a tuple, then the axis must be a tuple of the same size, and each of the given axes is shifted by the corresponding number. If an int while the axis is a tuple of ints, then the same value is use for all given axes.
  • axis: [array_like] Plane, along which we wish to roll array or shift its elements.

Return: Output rolled array, with the same shape as a.

Let’s have a look at some code snippets.

Code Examples of NumPy roll

Example 01:

# welcome to softhunt.net
# Python Program illustrating
# numpy.roll() method

import numpy as np

array = np.arange(9).reshape(3, 3)
print("Original array : \n", array)

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

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

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

Output:

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

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

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

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

FAQs

What is Rollaxis?

The numpy.rollaxis() function rolls the specified axis backward until it lies in a given position.

How do I shift in NumPy?

The numpy.roll() function in Python may be use to right-shift or left-shift the elements of a NumPy array. To roll array elements along a defined axis, use the numpy.roll() function. It produces the shifted array after taking the array and the number of places we want to move the items of the array. We must use a positive integer as the shift value if we wish to move the components to the right. If we want the items to shift to the left, we must use a negative shift value. 

Conclusion

That’s all for this article, if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn. And make sure you check out our NumPy tutorials.

Suggested Articles:

  1. Python NumPy flip array Function

Leave a Comment