圆形阵列上的滚动窗口

ale*_*dro 5 python arrays numpy circular-list

我想将给定的函数(特别是 np.std())应用于测量数组,并且我想将其应用于给定大小的滚动窗口。

但是 - 由于测量是在圆形阵列中 - 我还需要滚动窗口能够从阵列末端重叠到其开头。

因此,我无法在 Numpy 中的 1D 数组滚动窗口中使用答案?...我尝试修改它的方法,但我不是 numpy 专家,我无法理解 np.lib.stride_tricks.as_strided 的作用(它的文档在哪里???)

unu*_*tbu 6

用足够的值填充原始数组以形成“伪循环”数组。然后应用rolling_window到伪循环数组:

import numpy as np

def rolling_window(a, window):
    # http://www.mail-archive.com/numpy-discussion@scipy.org/msg29450.html
    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)

def circular_rolling_window(a, window):
    pseudocircular = np.pad(a, pad_width=(0, windowsize-1), mode='wrap')
    return rolling_window(pseudocircular, windowsize)

a = np.arange(5)
windowsize = 3
print(circular_rolling_window(a, windowsize))
Run Code Online (Sandbox Code Playgroud)

产量

[[0 1 2]
 [1 2 3]
 [2 3 4]
 [3 4 0]
 [4 0 1]]
Run Code Online (Sandbox Code Playgroud)