Skip to content

Instantly share code, notes, and snippets.

@codehacken
Last active October 16, 2021 03:29
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codehacken/708f19ae746784cef6e68b037af65788 to your computer and use it in GitHub Desktop.
Save codehacken/708f19ae746784cef6e68b037af65788 to your computer and use it in GitHub Desktop.
Create a Sliding Window function using NumPy.
# Create a function to reshape a ndarray using a sliding window.
# NOTE: The function uses numpy's internat as_strided function because looping in python is slow in comparison.
# Adopted from http://www.rigtorp.se/2011/01/01/rolling-statistics-numpy.html
import numpy as np
# Reshape a numpy array 'a' of shape (n, x) to form shape((n - window_size), window_size, x))
def rolling_window(a, window, step_size):
shape = a.shape[:-1] + (a.shape[-1] - window + 1 - step_size + 1, window)
strides = a.strides + (a.strides[-1] * step_size,)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
@Ajk4
Copy link

Ajk4 commented Aug 18, 2019

FYI internet

There is off-by-one bug in this code. Last window is getting dropped.

I recommend this implementation that works correctly -> https://stackoverflow.com/a/6811241

@b3nab
Copy link

b3nab commented Nov 28, 2019

Just edit the line #9 and add a +1 for the step_size

    shape = a.shape[:-1] + (a.shape[-1] - window + 1 - step_size + 1, window)

@codehacken
Copy link
Author

Thanks for the change. I'll update the code accordingly.

@engividal
Copy link

I tested the code but still wrong:

x = np.asarray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
rolling_window(x, 3, 2)

Result:

array([[ 1, 3, 5], [ 2, 4, 6], [ 3, 5, 7], [ 4, 6, 8], [ 5, 7, 9], [ 6, 8, 10], [ 7, 9, 11], [ 8, 10, 12], [ 9, 11, 13], [10, 12, 14], [11, 13, 15], [12, 14, 0]])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment