首页 > 解决方案 > 来自numpy table-ish数组的numpy滚动windows

问题描述

我有下表类似的 6x3 numpy 数组:

array([[1, 4, 1],
       [2, 2, 3],
       [3, 5, 6],
       [4, 8, 5],
       [5, 2, 7],
       [6, 4, 8]])

我试图获得滚动窗口,例如大小为 4(意思是每个窗口有 4 行),如下所示:

array([[[1, 4, 1],
        [2, 2, 3],
        [3, 5, 6],
        [4, 8, 5]],

       [[2, 2, 3],
        [3, 5, 6],
        [4, 8, 5],
        [5, 2, 7]],

       [[3, 5, 6],
        [4, 8, 5],
        [5, 2, 7],
        [6, 4, 8]]])

什么是实现这一目标的有效方法?

最终,我想构建一个这样的函数:

def rolling_windows(arr, windows_size):
    return all windows of size "window_size" of the table-ish np.array "arr"

我尝试使用np.lib.stride_tricks,但没有成功...

感谢您的帮助

标签: pythonnumpy

解决方案


推荐阅读