python中的滚动窗口

2024-04-13

我有一个 numpy 数组。我需要一个滚动窗口:[1,2,3,4,5,6]子数组长度 3 的预期结果:[1,2,3] [2,3,4] [3,4,5] [4,5,6]能否请你帮忙。我不是 python 开发者。

Python 3.5


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]])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python中的滚动窗口 的相关文章

随机推荐