If numpy
不是必需的,您可以只使用列表理解。如果x
是你的数组,那么:
In [102]: [x[i: i + 3] for i in range(len(x) - 2)]
Out[102]: [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
或者,使用np.lib.stride_tricks
。定义一个函数rolling_window
(来源自这个博客 http://www.rigtorp.se/2011/01/01/rolling-statistics-numpy.html):
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)
调用该函数window=3
:
In [122]: rolling_window(x, 3)
Out[122]:
array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6]])