Created
March 14, 2019 22:14
-
-
Save tclements/7452c0fac3e66e08b886300b4e24e687 to your computer and use it in GitHub Desktop.
Create a Sliding Window function (with steps) 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 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