AppDividend
Latest Code Tutorials

Numpy roll: How to Roll Elements Along Axis in Python

Numpy roll() function is used for rolling array elements along a specified axis i.e., elements of an input array are being shifted. If the item is being rolled first to last-position, it is rolled back to the first position.

Numpy roll()

NumPy roll() function is defined under NumPy, which can be imported as import NumPy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of NumPy, which is a library in Python.

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, then 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 array or shift its elements.

Return Value

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

Examples

Write a program to show the working of the Numpy.roll() function.

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]]

Explanation

In the above program, An array is created with an arange function and reshape function.

Arange function created an array with 12 elements starting from 0 to 11, and the reshape function made a matrix with 3 rows and 4 columns.

1st function is used for shifting all its elements by 1 time.

2nd function is used for shifting all its elements by 4 times.

3rd function is used for shifting all its elements by 5 times w.r.t 0 axis.

Conclusion

Numpy.roll(array, shift, axis = None) function Roll array elements along the specified axis. What happens is that elements of the input array are being shifted.

If an element is being rolled first to last-position, it is rolled back to the first position.

See also

NumPy ravel()

NumPy compress()

NumPy reshape()

NumPy place()

NumPy identity()

Leave A Reply

Your email address will not be published.

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