python - 在 Pandas 中进行分组和插值
问题描述
我有包含周数、帐户 ID 和几个使用列的数据。我想a)按帐户ID分组,b)将每周数据重新采样为每日数据,c)平均插入每日数据(每周除以7),然后将它们全部重新组合在一起。我已经把大部分内容都记下来了,但是 Pandasgroupby
让我有点困惑。它也很慢,这让我认为这可能不是最佳解决方案。
数据如下所示:
Account Id year week views stats foo_col
31133 213 2017-03-05 4.0 2.0 11.0
10085 456 2017-03-12 1.0 6.0 3.0
49551 789 2017-03-26 1.0 6.0 27.0
这是我的代码:
def interpolator(mini_df):
mini_df = mini_df[cols_to_interpolate].set_index('year week')
return mini_df.resample('D').ffill().interpolate() / 7
example = list(grp)[0][1]
interpolator(example) # This works perfectly
df.groupby('Account Id').agg(interpolator) # doesn't work
df.groupby('Account Id').transform(interpolator) # doesn't work
for name,group in grp:
group = group[cols_to_interpolate].set_index('year week')
group = group.resample('D').ffill().interpolate() / 7 # doesn't work
for acc_id in df['Account Id'].unique():
mask = df.loc[df['Account Id'] == acc_id]
print(df[mask]) # doesn't work
解决方案
我希望你的函数应该与groupby
像这样的对象链接:
df = (df.set_index('year week')
.groupby('Account Id')[cols_to_interpolate]
.resample('D')
.ffill()
.interpolate() / 7)
来自评论的解决方案是不同的 -interpolate
适用于每个组:
df.groupby('Account Id').apply(interpolator)
推荐阅读
- notepad++ - 如何删除文本后 | 记事本++中的字符
- json - 从 SQL Server NVARCHAR 列中提取 JSON 值
- android - Ionic 3 应用程序 - 如何使字体大小独立于本机设置?
- okhttp - 如何设置 OkHttp 来请求压缩资源而不是解压缩它们
- php - Laravel 不规则复数模型名称
- r - 了解 r 中 durbinWatsonTest() 的输出
- biztalk - 无法将绑定文件导入 Biztalk 管理控制台
- c# - 类型中的成员类型与 EF 中类型中的成员类型不兼容
- javascript - 在javascript中散列一个值 - 可以反转吗?
- javascript - 如何将 commonjs 模块添加到 Nuxt 项目?