Last active
June 21, 2016 03:08
-
-
Save dmyersturnbull/7747f658a78b865ae54d5bfeee552d49 to your computer and use it in GitHub Desktop.
Quickly calculate a sliding window of a Numpy array.
This file contains hidden or 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
| 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