python - Pandas 中的窗口重叠

标签 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 中包含的优化方法来做到这一点?

最佳答案

使用 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)

如果您将一维数组传递给上述函数,它将返回该数组的二维 View ,形状为 (number_of_windows, window_size),因此您可以计算,例如窗口意味着:

win_avg = np.mean(windowed_view(arr, win_size, win_overlap), axis=-1)

例如:

>>> 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]])

关于python - Pandas 中的窗口重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18247009/

相关文章:

c# - 修改一个点,UnboundNameException

python - 将 csv 导入 dask 中的数据框时命名列

python - 根据每个单独数据帧的行索引(编号)连接/加入/合并多个数据帧

python线性回归以日期为轴

python ,Seaborn : Plotting frequencies with zero-values

python - 全局名称 'unhex' 未定义

python - 从 WebDriver 元素检索属性

python - DB-Connections 类作为 Python 中的单例

python cv2数组到numpy

Python scikit-learn : Cannot clone object. .. 因为构造函数似乎没有设置参数