If an element is shifted from the first to the last position, it is moved back to the first position.
Let us explore the roll function in NumPy.
The function syntax is as shown below:
The parameters are as shown:
- a – defines the input array.
- shift – refers to the number of places by which the elements in the array are shifted.
- axis – the axis along which the specified elements are to be shifted.
Function Return Value
The function returns an array with the elements in the specified axis shifted by the factor specified in the shift parameter.
NOTE: The output array holds the same shape as the input array.
Consider the example code shown below:
The code above shows how to use the roll function to shift the elements in a 2D array by a factor of 1 along the 0 axis.
The resulting output is as shown:
Consider another example that performs the same operation along axis 1.
In this case, the roll function performs the shift operation along axis 1 and returns:
The code below illustrates how to use the roll function to shift the elements in the array to 5 places.
Here, we set the shift parameter to 5 and the axis as 0. The resulting array is as shown:
You can also specify the shift value as a tuple. In such a case, the axis must be a tuple of the same size.
Take the example code below:
The code above should return:
In this article, we discussed the NumPy roll function, what it is, its parameters, and return values. We also demonstrated how to use the function using various examples.