在熊猫的窗口重叠

Rob*_*ith 6 python numpy pandas

在pandas中,有几种方法可以在给定的窗口中操作数据(例如pd.rolling_meanpd.rolling_std.)但是,我想设置窗口重叠,我认为这是一个非常标准的要求.例如,在下图中,您可以看到一个跨越256个样本并重叠128个样本的窗口.

http://health.tau.ac.il/Communication%20Disorders/noam/speech/mistorin/images/hamming_overlap1.JPG

如何使用Pandas或Numpy中包含的优化方法来做到这一点?

Jai*_*ime 6

使用as_strided你会做这样的事情:

import numpy as np
from numpy.lib.stride_tricks import as_strided

def windowed_view(arr, window, overlap):
    arr = np.asarray(arr)
    window_step = window - overlap
    new_shape = arr.shape[:-1] + ((arr.shape[-1] - overlap) // window_step,
                                  window)
    new_strides = (arr.strides[:-1] + (window_step * arr.strides[-1],) +
                   arr.strides[-1:])
    return as_strided(arr, shape=new_shape, strides=new_strides)
Run Code Online (Sandbox Code Playgroud)

如果将一维数组传递给上面的函数,它会将2D视图返回到具有形状的数组中(number_of_windows, window_size),因此您可以计算,例如窗口均值为:

win_avg = np.mean(windowed_view(arr, win_size, win_overlap), axis=-1)
Run Code Online (Sandbox Code Playgroud)

例如:

>>> a = np.arange(16)
>>> windowed_view(a, 4, 2)
array([[ 0,  1,  2,  3],
       [ 2,  3,  4,  5],
       [ 4,  5,  6,  7],
       [ 6,  7,  8,  9],
       [ 8,  9, 10, 11],
       [10, 11, 12, 13],
       [12, 13, 14, 15]])
>>> windowed_view(a, 4, 1)
array([[ 0,  1,  2,  3],
       [ 3,  4,  5,  6],
       [ 6,  7,  8,  9],
       [ 9, 10, 11, 12],
       [12, 13, 14, 15]])
Run Code Online (Sandbox Code Playgroud)