Skip to content

Instantly share code, notes, and snippets.

@tclements
Created March 14, 2019 22:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tclements/7452c0fac3e66e08b886300b4e24e687 to your computer and use it in GitHub Desktop.
Save tclements/7452c0fac3e66e08b886300b4e24e687 to your computer and use it in GitHub Desktop.
Create a Sliding Window function (with steps) using NumPy.
# Create a function to reshape a 1d array using a sliding window with a step.
# 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 and
# https://gist.github.com/codehacken/708f19ae746784cef6e68b037af65788
import numpy as np
# Reshape a numpy array 'a' of shape (x) to form shape((n - window_size) // step + 1, window_size))
def rolling_window(a, window, step):
shape = a.shape[:-1] + ((a.shape[-1] - window + 1)//step, window)
strides = (a.strides[0] * step,) + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment