Rolling windows for ndarrays

回眸只為那壹抹淺笑 提交于 2021-01-28 09:00:37

问题


I have a ndimensional array with shape (30,2,2) and 2000 elements. So my final array is of shape (2000, 30, 2, 2). I now want to stack rolling 200 elements in a new array. So I assume my final array will look something like (1801, 200, 30, 2, 2) where each element in 1800 has 200 samples of (30,2,2) arrays. How do you create this rolling window in python. I have tried using vstack but not entirely sure how I achieve my desired results.

import numpy as np

input = np.zeros((2000, 30, 2, 2))
desired_output = np.zeros((1801, 200, 30, 2, 2))

回答1:


We can leverage np.lib.stride_tricks.as_strided based scikit-image's view_as_windows to get sliding windows and hence solve our case here. More info on use of as_strided based view_as_windows.

The output would be a view into the input array and as such, it's virtually free on runtime. The implementation would be -

from skimage.util.shape import view_as_windows

out = view_as_windows(input,(200,1,1,1))[...,0,0,0].transpose(0,4,1,2,3)



回答2:


You can slice the first dimension and stack window sized arrays together using numpy.stack:

import numpy as np

a = np.zeros((2000, 30, 2, 2))

ws = 200
n = a.shape[0]

r = np.stack([a[i:i+ws] for i in range(n-ws+1)])
r.shape
(1801, 200, 30, 2, 2)


来源:https://stackoverflow.com/questions/61711831/rolling-windows-for-ndarrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!