Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Python 3.5

like image 922
Boppity Bop Avatar asked Jan 19 '26 18:01

Boppity Bop


2 Answers

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] for i in range(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]])
like image 136
cs95 Avatar answered Jan 22 '26 07:01

cs95


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]
like image 27
Ananaz Avatar answered Jan 22 '26 07:01

Ananaz