numpy.roll() is a function in the Python numpy library and allows you to roll (rotate) an array’s elements along a given axis.
First, let's define what we mean by "rolling" an array. When we roll an array, we're essentially shifting its elements along a particular axis. This can be useful in a variety of scenarios, such as circularly shifting the elements of an array or reordering them in a specific way.
The numpy.roll() function provides a convenient way to perform these operations. Its syntax is simple: numpy.roll(arr, shift, axis=None). Here, arr is the array we want to roll, shift is the number of places by which we want to shift the elements, and axis specifies the axis along which we want to roll the array. If axis is not specified, all dimensions of the array will be rolled.
Let us try it out!
Here we have a Python list (called temperatures) and we are rolling this list (by 2 positions to the right) which will return an array. Because we are rolling by 2 positions, the 2 values that we push out of the list (array) will get added to the front of the array. So the output will be:
Note that 75.4 and 81.3 are now in the beginning of the numpy array.
You can also try rolling in the opposite direction by giving a negative offset:
The output is as expected:
Let us now try rolling a two dimensional array!
Here we are creating an array (denoting a magic square of numbers). The axis=0 specifies that we are only rolling the rows. Thus, the rows of the array have been shifted by one place, with the last row being moved to the beginning of the array. The output is:
Let us now try rolling only the columns!
The output is:
Note that if you roll with an offset equal to the size of the dimension, you will obtain the same array back. Thus if we change the above program as:
it will yield:
This is because rolling along the column dimension 3 times gives the same array back.
Finally, you can roll along both axes, with specific offsets, like so:
Here we are rolling along both dimensions. Along the rows (ie axis=0) we are rolling by 1. Along the columns (i.e., axis=1) we are rolling by 3 (so they will be unchanged). The output is:
i.e., what we obtained in our first program earlier.
These are just a few examples of how numpy.roll() can be used to manipulate array elements in Python. With this powerful tool at your disposal, you can easily perform a variety of data manipulation tasks, such as circularly shifting an array or reordering its elements in a specific way.
In conclusion, numpy.roll() is a must-have tool for anyone working with arrays in Python. Its versatility and ease of use make it an indispensable part of the numpy library, and its powerful functionality can help you accomplish a wide variety of data manipulation tasks with ease.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.