Numpy roll allows you to shift the elements of the NumPy array. It rolls the elements along the given axis. In this post, you will learn how to use the NumPy roll to shift NumPy array elements to the left or right for both 1D and 2D array.
Syntax of Numpy Roll Function
numpy.roll(a, shift, axis=None)
Explanation of the Parameter
a: It is the input array, can accept a 1D or 2D array.
shift: It is a positive or negative integer. The number of places you want to shift.
axis: Allows you to do shifting along rows or columns.
Steps to Implement Numpy Roll
Step 1: Import all the necessary libraries
In this article, I am using only NumPy modules. So let’s import them.
import numpy as np
Step 2: Create a Sample Numpy Array
In this step, I am creating both 1D and 2D NumPy arrays. I will implement the NumPy roll function on both of them.
1D Numpy array
array_1d = np.array([1,2,3,4,5,6,7])

2D Numpy array
array_2d = np.array([[1,2,3],[4,5,6],[7,8,9]])

Step 3: Implement the Numpy roll on the array
After the creation of the NumPy array let’s implement numpy.roll() method on them.
Applying Numpy Roll on a 1D array
Let’s shift the NumPy elements to 1 place. Then I will shift to 2 places and 3 places.
Shifting to 1 place
np.roll(array_1d,1)
Output

Here the last element will come to the first and remaining shift rightward.
Shifting to 2 place
np.roll(array_1d,2)
Output

The above code will shift the last two elements to the first and the remaining will shift right.
Shift to 3 Place
To shift the last three elements to the right use shift =3.
np.roll(array_1d,3)
Output

In the same, if you want to shift the elements leftward then pass the shift value as negative. For example, If I will use shift =-1, then the first element will become the last element and the remaining will shift left.
Applying Numpy Roll on a 2D array
Implementing numpy.roll on 2D NumPy array is different from 1D. Here We have three cases.
Case 1: Apply roll() without axis
If you apply roll on a 2D array without axis. Then all the elements will be shifted right or left.
np.roll(array_2d,1)
Output

Case 2: Apply roll() without axis =0
Applying roll() with axis=0, will shift the elements of each column downward or upwards.
np.roll(array_2d,1,axis=0)
Output

Case 3: Apply roll() without axis =1
In case 3, if you set the value of axis to 1, then the shifting of the elements will take place row-wise or horizontally.
np.roll(array_2d,1,axis=1)
Output

Conclusion
Numpy roll allows reducing the time of indexing for a certain element in the array. You just shift the elements and then index it. Thus increase efficiency. These are the steps to implement the roll. Hope you have liked this article. If you have any queries then you can contact us.
Source:
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.