Created
February 11, 2020 11:17
-
-
Save thibthibaut/353556f2dedcef63dcdb54df1c898662 to your computer and use it in GitHub Desktop.
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 | |
#https://stackoverflow.com/questions/6811183/rolling-window-for-1d-arrays-in-numpy/6811241#6811241 | |
def rolling_window(a, window): | |
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) | |
strides = a.strides + (a.strides[-1],) | |
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) | |
a = np.array(range(20)) | |
print( rolling_window(a, 4) ) | |
# array([[ 0, 1, 2, 3], | |
# [ 1, 2, 3, 4], | |
# [ 2, 3, 4, 5], | |
# [ 3, 4, 5, 6], | |
# [ 4, 5, 6, 7], | |
# [ 5, 6, 7, 8], | |
# [ 6, 7, 8, 9], | |
# [ 7, 8, 9, 10], | |
# [ 8, 9, 10, 11], | |
# [ 9, 10, 11, 12], | |
# [10, 11, 12, 13], | |
# [11, 12, 13, 14], | |
# [12, 13, 14, 15], | |
# [13, 14, 15, 16], | |
# [14, 15, 16, 17], | |
# [15, 16, 17, 18], | |
# [16, 17, 18, 19]]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment