Skip to content

Instantly share code, notes, and snippets.

@dmyersturnbull
Last active June 21, 2016 03:08
Show Gist options
  • Save dmyersturnbull/7747f658a78b865ae54d5bfeee552d49 to your computer and use it in GitHub Desktop.
Save dmyersturnbull/7747f658a78b865ae54d5bfeee552d49 to your computer and use it in GitHub Desktop.
Quickly calculate a sliding window of a Numpy array.
import numpy as np
def sliding_window(x: np.ndarray, n: int) -> np.ndarray:
"""Returns a sliding window of n elements from x.
Raises a ValueError of n > len(x).
"""
if n > len(x): raise ValueError("N must be less than the array length")
# Courtesy of https://stackoverflow.com/questions/13728392/moving-average-or-running-mean
return np.convolve(x, np.ones((n,)) / n, mode='valid')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment