python - 如何让 Pandas 在非均匀 x 网格上执行滚动平均

标签 python pandas numpy scipy

我想执行滚动平均值,但窗口在 x 中只有有限的“视觉”。我想要类似于下面的内容,但我想要一个基于 x 值而不是位置索引的窗口范围。
虽然在 Pandas 中这样做是首选,但 numpy/scipy 等价物也可以

import numpy as np 
import pandas as pd 

x_val = [1,2,4,8,16,32,64,128,256,512]
y_val = [x+np.random.random()*200 for x in x_val]

df = pd.DataFrame(data={'x':x_val,'y':y_val})
df.set_index('x', inplace=True)

df.plot()
df.rolling(1, win_type='gaussian').mean(std=2).plot()
所以我希望前 5 个值被平均在一起,因为它们彼此相差 10 个 xunits,但最后一个值保持不变。

最佳答案

关键问题仍然是:您希望通过滚动方式实现什么?
从数学上讲,一种干净的方法是:

  • 插值到 x 数据的最佳 dx
  • 执行滚动平均值
  • 取出你想要的数据点(但要小心:这一步也是一种平均!)

  • 这是插值的代码:
    import numpy as np 
    import pandas as pd 
    import matplotlib.pyplot as plt
    from scipy.interpolate import interp1d
    
    x_val = [1,2,4,8,16,32,64,128,256,512]
    y_val = [x+np.random.random()*200 for x in x_val]
    
    df = pd.DataFrame(data={'x':x_val,'y':y_val})
    df.set_index('x', inplace=True)
    
    #df.plot()
    df.rolling(5, win_type='gaussian').mean(std=200).plot()
    
    
    #---- Interpolation -----------------------------------
    f1 = interp1d(x_val, y_val)
    f2 = interp1d(x_val, y_val, kind='cubic')
    
    dx = np.diff(x_val).min()  # get the smallest dx in the x-data set
    
    xnew = np.arange(x_val[0], x_val[-1]+dx, step=dx)
    ynew1 = f1(xnew)
    ynew2 = f2(xnew)
    
    #---- plot ---------------------------------------------
    fig = plt.figure(figsize=(15,5))
    plt.plot(x_val, y_val, '-o', label='data', alpha=0.5)
    plt.plot(xnew, ynew1, '|', ms = 15, c='r', label='linear', zorder=1)
    #plt.plot(xnew, ynew2, label='cubic')
    plt.savefig('curve.png')
    plt.legend(loc='best')
    plt.show()
    
    enter image description here

    关于python - 如何让 Pandas 在非均匀 x 网格上执行滚动平均,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64897689/

    相关文章:

    Python:创建数组的 "negative"

    python - 在字符串时获取列中的索引最小值 - Pandas Dataframe

    python - 如何使用 python 使用位移运算符找出以 2 为基数的数字的某个数字?

    json - Pandas 数据框到JSON列表格式

    python - 为什么当我更改一个变量时,两个变量都会更改? Python

    python - 计算范围内的出现次数

    Python 服务文件缓存 Apache 竞态条件

    python - Kubernetes 集群中的 FileNotFoundError Python-Flask/Docker

    python - 从字符串列表中查找最常见的单词

    python - 根据规则获取字典的键