Skip to content Skip to sidebar Skip to footer

Rolling Window In Python

I have a numpy array. I need a rolling window: [1,2,3,4,5,6] expected result for sub array length 3: [1,2,3] [2,3,4] [3,4,5] [4,5,6] Could you please help. I am not a python dev

Solution 1:

If numpy is not a necessity, you can just use a list comprehension. If x is your array, then:

In[102]: [x[i: i + 3]foriinrange(len(x) - 2)]
Out[102]: [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]

Alternatively, using np.lib.stride_tricks. Define a function rolling_window (source from this blog):

def rolling_window(a, window):
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

Call the function with window=3:

In [122]: rolling_window(x, 3)
Out[122]: 
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6]])

Solution 2:

This might also be interesting: The view_as_windows() function from the skimage.util module. It returns a

rolling window view of the input n-dimensional array.

Source: https://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.view_as_windows

Directly from the linked examples (adapted for your range of numbers):

>>> import numpy as np
>>> from skimage.util import view_as_windows
>>>
>>> A = np.arange(1,7)
>>> A
array([1, 2, 3, 4, 5, 6])
>>> window_shape = (3,)
>>> B = view_as_windows(A, window_shape)
>>> B.shape
(4, 3)
>>> for win in B:
        print(win)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]

Post a Comment for "Rolling Window In Python"