如何创建一个与numpy数组重叠50%的滑动窗口?

时间:2017-08-17 08:47:28

标签: arrays numpy sliding-window

说我有一个这样的数组:

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

我想将其更改为

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

此处窗口大小为4,步长为2

如何在Python函数中执行此操作?

1 个答案:

答案 0 :(得分:6)

您需要numpy.lib.stride_tricks.as_strided

def window(a, w = 4, o = 2, copy = False):
    sh = (a.size - w + 1, w)
    st = a.strides * 2
    view = np.lib.stride_tricks.as_strided(a, strides = st, shape = sh)[0::o]
    if copy:
        return view.copy()
    else:
        return view

Out[]: 
array([[ 1,  2,  3,  4],
       [ 3,  4,  5,  6],
       [ 5,  6,  7,  8],
       [ 7,  8,  9, 10]])

如果要写入窗口数组,请务必设置copy = True,否则它是内存共享视图。