Last active
June 19, 2024 21:11
-
-
Save codehacken/708f19ae746784cef6e68b037af65788 to your computer and use it in GitHub Desktop.
Create a Sliding Window function using NumPy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
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)
Thanks for the change. I'll update the code accordingly.
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
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