【问题标题】:Finding the mean value (or rolling average) of a scattered dataset with Python使用 Python 查找分散数据集的平均值(或滚动平均值)
【发布时间】: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()

所以蓝色是我的数据 - 红色是平均值应该是什么样子(在这个测试用例中我显然知道),绿色是样条方法会给我的。

肯定有人知道通过智能(内置)算法实现红色曲线的更好方法吗?

【问题讨论】:

标签: python pandas numpy average


【解决方案1】:

你可以roundx 值然后groupby 得到平均值。

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.interpolate import UnivariateSpline

# generate testdata
def testdata(x):
    return 1/(1+10.*x**2)

# create x, y
x = np.random.uniform(-1,1,1000)
y = testdata(x) + np.random.normal(0, 1, len(x))

# convert to df and sort values inplace
df = pd.DataFrame({'x': x, 'y': y})
df.sort_values(by='x', inplace=True)

# round x values then group by to create bins
round_by = 2
bins = df.groupby(df.x.round(round_by)).mean()

# plot
fig, ax = plt.subplots()

ax.scatter(df.x, df.y, s=1)
plt.plot(bins.index, bins.y, 'g--', lw=3)

plt.show()

【讨论】:

  • 谢谢。但老实说,与我上面的解决方案有什么不同?写的风格不同,但内容相同。
  • 我的错。我误解了这个问题。我已经更新了答案。这是你想要的吗?
  • 不用担心。我只是在寻找方法的差异。是的,您的更改有点帮助,因为我未能生成一些合适的垃圾箱。您使用 round() 的想法对此有所帮助。
  • 嘿,尝试df['group'] = pd.cut(df.x, 10) 从连续范围创建类别,然后bins = df.groupby(df.group).mean() 获得每个类别的平均值。祝你好运!
猜你喜欢
  • 2021-12-22
  • 1970-01-01
  • 2021-06-04
  • 2014-11-29
  • 2018-05-08
  • 2013-05-07
  • 1970-01-01
相关资源
最近更新 更多