Skip to content

Instantly share code, notes, and snippets.

@codehacken
codehacken / sliding_window.py
Last active October 16, 2021 03:29
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,)