The roll() method shifts the elements of the input arrays a given number of times.
If an element goes beyond the boundary of the array, it wraps around and returns to the start of the array.
roll() Syntax
The syntax of roll() is:
numpy.roll(array, shift, axis)
roll() Arguments
The roll() method takes three arguments:
array- an array with elements to be rolledshift- how many steps the element shifts (intortuple)axis(optional) - axis to roll/shift (intortuple)
roll() Return Value
The roll() method returns the array with elements shifted.
Example 1: Roll a 1-D Array
Output
[2 3 4 0 1] [1 2 3 4 0]
Here, array3 is rolled by a negative value (-1), so it's shifted backward.
Example 2: Roll a 2-D Array
A 2-D array can be rolled on two axes. If the array is rolled on axis 0, it shifts vertically and if the array is rolled on axis 1, it shifts horizontally.
Output
Roll one step: [[5 0 1] [2 3 4]] Roll on axis 0: [[3 4 5] [0 1 2]] Roll on axis 1: [[2 0 1] [5 3 4]] Roll on both axes: [[5 3 4] [2 0 1]]
If the axis is not provided, the array is flattened, rolled, and reshaped back to its original shape.
Example 3: Roll a 2-D Array on Both Axes With Different Numbers of Shifts
The roll() method allows us to shift elements along multiple axes by specifying the number of times we want to roll each axis.
We can apply different rolling operations to different axes of an array.
Output
Default roll: [[6 7 8] [0 1 2] [3 4 5]] Roll with (0,1) axes: [[6 7 8] [0 1 2] [3 4 5]]
The default axis is (0, 1). With the shift of (1, 2), the array shifts by 1 step in axis-0 and 2 steps in axis-1.