2

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

2 Answers 2

8

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]])
Sign up to request clarification or add additional context in comments.

Comments

3

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.