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]])