我有一个numpy的数组。我需要一个滚动窗口:
[1,2,3,4,5,6]
子数组长度3的预期结果:
[1,2,3] [2,3,4] [3,4,5] [4,5,6]
请您帮忙。我不是python开发人员。
Python 3.5
如果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]]
Run Code Online (Sandbox Code Playgroud)
或者,使用np.lib.stride_tricks。定义一个函数rolling_window(此博客的源代码):
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)
Run Code Online (Sandbox Code Playgroud)
用以下命令调用该函数window=3:
In [122]: rolling_window(x, 3)
Out[122]:
array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6]])
Run Code Online (Sandbox Code Playgroud)