pandas - 使用加权平均值对数据框中的数据进行重新采样
问题描述
我有一个包含基于时间的数据的数据框,我需要按 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。任何人都知道这个对象是什么以及如何在加权平均函数中使用输出?
或者也许我可以使用另一种方法?
解决方案
遍历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
推荐阅读
- php - 将 PHP 过滤数组发布到 API 的问题
- javascript - 我如何更好地编写这个reportCandidates的功能?
- vue.js - 如何在 Vuex 插件中观察突变
- python - 如何安排python脚本在给定时间退出
- vue.js - 在 Vue.js 中,如何取消链接一组单选按钮?
- python - 从单个脚本运行多个 python 脚本,并在它们之间来回通信?
- javascript - AJAX自动刷新/提交按钮后不刷新页面 - HTML / PHP
- css - 如何像普通 HTML 文本或任何其他文本编辑器一样光标选择 SVG/d3.js 文本?
- css - 三星上网匹配 justify-content: space-evenly 但不支持
- c# - Grid 设置了 PreviewMouseMove 时 WPF 按钮事件未触发