【发布时间】:2018-01-20 13:55:14
【问题描述】:
我有一个 numpy 数组。我需要一个滚动窗口:
[1,2,3,4,5,6]
子数组长度 3 的预期结果:
[1,2,3] [2,3,4] [3,4,5] [4,5,6]
能否请你帮忙。我不是 python 开发者。
Python 3.5
【问题讨论】:
标签: python python-3.x
我有一个 numpy 数组。我需要一个滚动窗口:
[1,2,3,4,5,6]
子数组长度 3 的预期结果:
[1,2,3] [2,3,4] [3,4,5] [4,5,6]
能否请你帮忙。我不是 python 开发者。
Python 3.5
【问题讨论】:
标签: python python-3.x
这可能也很有趣:skimage.util 模块中的 view_as_windows() 函数。它返回一个
输入 n 维数组的滚动窗口视图。
来源:https://scikit-image.org/docs/dev/api/skimage.util.html#skimage.util.view_as_windows
直接来自链接示例(适用于您的数字范围):
>>> import numpy as np
>>> from skimage.util import view_as_windows
>>>
>>> A = np.arange(1,7)
>>> A
array([1, 2, 3, 4, 5, 6])
>>> window_shape = (3,)
>>> B = view_as_windows(A, window_shape)
>>> B.shape
(4, 3)
>>> for win in B:
print(win)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
【讨论】:
如果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]])
【讨论】: