【发布时间】:2021-03-03 20:16:56
【问题描述】:
我有一个代表分散功能行为的大型两列数据集。假设对于每个时间值 (x),存在一定数量的广泛分布的测量值 (y)。我想为每个时间值(或考虑特定时间间隔内的直方图)获得其中测量值 y 的平均值。我正在寻找滚动/移动平均线和样条插值,但我被卡住了。以下是应该发生的事情的最小示例代码:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.interpolate import UnivariateSpline
#generate testdata which usually is read in from a huge file
def testdata(x):
return 1/(1+10.*x**2)
x = np.random.uniform(-1,1,1000)
y = testdata(x) + np.random.normal(0, 1, len(x))
#convert it to dataframes, as I usually work with them
df = pd.DataFrame(list(zip(x,y)))
#sort the x-values as they are randomly distributed in the dataset
df_new = df.sort_values(by=[0])
#show the data and how the (analytical average shhould look like)
plt.scatter(df_new[0],df_new[1],s=1)
plt.scatter(df_new[0],testdata(df_new[0]), s=1, c='r')
#try a spline - however it fails
spl = UnivariateSpline(df_new.iloc[:, 0], df_new.iloc[:, 1])
xs = np.linspace(-1, 1, 10000)
plt.plot(xs, spl(xs), 'g--', lw=3)
plt.show()
所以蓝色是我的数据 - 红色是平均值应该是什么样子(在这个测试用例中我显然知道),绿色是样条方法会给我的。
肯定有人知道通过智能(内置)算法实现红色曲线的更好方法吗?
【问题讨论】:
-
看看 pandas 的 .rolling() 函数。 pandas.pydata.org/pandas-docs/stable/reference/api/…
标签: python pandas numpy average