numpy.roll() in Python
Last Updated :
08 Mar, 2024
The numpy.roll() function rolls array elements along the specified axis. Basically what happens is that elements of the input array are being shifted. 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 :
array : [array_like][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 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 axis is a tuple of ints, then the same value is used for all given axes.
axis : [array_like]Plane, along which we wish to roll array or shift it's elements.
Return :
Output rolled array, with the same shape as a.
Python
import numpy as geek
array = geek.arange( 12 ).reshape( 3 , 4 )
print ( "Original array : \n" , array)
print ( "\nRolling with 1 shift : \n" , geek.roll(array, 1 ))
print ( "\nRolling with 5 shift : \n" , geek.roll(array, 5 ))
print ( "\nRolling with 2 shift with 0 axis : \n" , geek.roll(array, 2 , axis = 0 ))
|
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 5 shift :
[[ 7 8 9 10]
[11 0 1 2]
[ 3 4 5 6]]
Rolling with 2 shift with 0 axis :
[[ 4 5 6 7]
[ 8 9 10 11]
[ 0 1 2 3]]
These codes won’t run on online IDE’s. So please, run them on your systems to explore the working.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...