首页 > 解决方案 > 使用加权平均值对数据框中的数据进行重新采样

问题描述

我有一个包含基于时间的数据的数据框,我需要按 12 小时和一天的周期对其进行重新采样。到目前为止,我正在使用以下代码:

if self.resample_by == 'day':
    self.model_df = self.model_df.resample('D', on='index').mean()
    self.model_df.dropna(axis=0, inplace=True)
elif self.resample_by == 'shift':
    delta = dt.timedelta(hours=12)
    self.model_df = self.model_df.resample(delta, on='24h_day_start').mean()
    self.model_df.dropna(axis=0, inplace=True)
else:
    pass

现在,正如您所看到的,我将mean()重采样数据用作权宜之计,但实际上不同的行具有不同的权重,因此我需要进行加权平均计算。

据我了解,我需要编写一个函数来计算加权平均值,然后使用apply(func)而不是mean(). 正确的?

然而,我不明白如何构造我的函数,因为我对DataFrame.resample实际返回的内容感到困惑。文档说该函数返回一个resampler object。任何人都知道这个对象是什么以及如何在加权平均函数中使用输出?

或者也许我可以使用另一种方法?

标签: pandasdataframe

解决方案


遍历groups属性。

rs = df.resample(...)

for group_name, group_labels in rs.groups.items():
    vals = rs.get_group(group_name)
    # apply weighted average function to vals df

重采样器对象的完整文档位于https://pandas.pydata.org/pandas-docs/stable/reference/resampling.html


推荐阅读