1
我有一个numpy数组。我需要一个滚动窗口: [1,2,3,4,5,6]
子阵列长度3的预期结果: [1,2,3] [2,3,4] [3,4,5] [4,5,6]
请你帮忙。我不是一个Python开发人员。Python中的滚动窗口
的Python 3.5
我有一个numpy数组。我需要一个滚动窗口: [1,2,3,4,5,6]
子阵列长度3的预期结果: [1,2,3] [2,3,4] [3,4,5] [4,5,6]
请你帮忙。我不是一个Python开发人员。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]]
另外,使用np.lib.stride_tricks
。定义一个函数rolling_window
(源从this blog):
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]])