| by Arround The Web | No comments

## NumPy np.roll

The NumPy roll function is used to roll elements in an input array along a specified axis. Rolling refers to the processing of shifting the position of the elements in a given array.

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.

## Function Syntax

The function syntax is as shown below:

numpy.roll(a, shift, axis=None)

The parameters are as shown:

1. a – defines the input array.
2. shift – refers to the number of places by which the elements in the array are shifted.
3. 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.

## Example 1

Consider the example code shown below:

import numpy as np
arr = np.array([[1,2,3], [4,5,6]])
print(f"original: {arr}")
print(f"shifted: {np.roll(arr, shift=1, axis=0)}")

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:

original: [[1 2 3]
[4 5 6]]
shifted: [[4 5 6]
[1 2 3]]

## Example 2

Consider another example that performs the same operation along axis 1.

arr = np.array([[1,2,3], [4,5,6]])
print(f"original: {arr}")
print(f"shifted: {np.roll(arr, shift=1, axis=1)}")

In this case, the roll function performs the shift operation along axis 1 and returns:

original: [[1 2 3]
[4 5 6]]
shifted: [[3 1 2]
[6 4 5]]

## Example 3

The code below illustrates how to use the roll function to shift the elements in the array to 5 places.

arr = np.array([[1,2,3], [4,5,6]])
print(f"original: {arr}")
print(f"shifted: {np.roll(arr, shift=5, axis=0)}")

Here, we set the shift parameter to 5 and the axis as 0. The resulting array is as shown:

original: [[1 2 3]
[4 5 6]]
shifted: [[4 5 6]
[1 2 3]]

## Example 5

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:

arr = np.arange(10).reshape(2,5)
print(f"original: {arr}")
print(f"shifted: {np.roll(arr, (2,1), axis=(1,0))}")

The code above should return:

original: [[0 1 2 3 4]
[5 6 7 8 9]]
shifted: [[8 9 5 6 7]
[3 4 0 1 2]]

## Closing

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.

Happy coding!!

Source: linuxhint.com