Creating n-shifted 2D Arrays

By using NumPy’s built-in functions and array manipulation techniques, we can build a two-dimensional array whose first row and each subsequent row are shifted by ‘n’ efficiently and with ease. This type of array is useful in many applications, such as image processing, computer vision, and data analysis. A few implementations are given below:

1. Using “np.stack()”:

The code defines a function called rolling that takes an array “a”, a window size “window”, and a value “n” as inputs. It then creates a new array by stacking slices of “a” that has a length “window”, with a stride of “n”.
Though it defines a function that rolls a NumPy array with a specified window size and offset, then applies it to a given array and displays the resulting rolled array, but it may not be easily adaptable to arrays with different shapes or data types.

2. Using “np.lib.stride_tricks.sliding_window_view()”:

This function uses NumPy’s sliding_window_view function(), which is a more convenient way to create sliding windows of an array. It returns a view of the input array with a sliding window of the specified size.
It is an efficient way to perform operations like moving averages, but it is limited to one-dimensional arrays and may not be suitable for more complex rolling window calculations.

Note: The following function only applies if you want to shift the array just by 1. And this function is only available in NumPy version 1.20 or later, if you have an earlier version of NumPy, you can use the np.lib.stride_tricks.as_strided() function.