Skip to content

Instantly share code, notes, and snippets.

@tclements
tclements / sliding_window.py
Created March 14, 2019 22:14
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)
@fanjin-z
fanjin-z / sliding_window_view.py
Last active November 21, 2023 16:40
Create sliding window views of the N dimensions array with the given window shape
'''
MIT License
Copyright (c) 2018 Fanjin Zeng
This work is licensed under the terms of the MIT license, see <https://opensource.org/licenses/MIT>.
'''
def sliding_window_view(x, shape, step=None, subok=False, writeable=False):
"""
Create sliding window views of the N dimensions array with the given window
shape. Window slides across each dimension of `x` and provides subsets of `x`