如何使用 7d 频率的 pandas 石斑鱼并用 0 填充缺失的天数? [英] How to use pandas Grouper with 7d frequency and fill missing days with 0?
本文介绍了如何使用 7d 频率的 pandas 石斑鱼并用 0 填充缺失的天数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下示例数据集
df = pd.DataFrame({
'names': ['joe', 'joe', 'joe'],
'dates': [dt.datetime(2019,6,1), dt.datetime(2019,6,5), dt.datetime(2019,7,1)],
'values': [5,2,13]
})
我想按 names
和按周或 7 天分组,我可以用
and I want to group by names
and by weeks or 7 days, which I can achieve with
df_grouped = df.groupby(['names', pd.Grouper(key='dates', freq='7d')]).sum()
values
names dates
joe 2019-06-01 7
2019-06-29 13
但是我要寻找的是这样的东西,带有所有明确的日期
But what I would be looking for is something like this, with all the explicit dates
values
names dates
joe 2019-06-01 7
2019-06-08 0
2019-06-15 0
2019-06-22 0
2019-06-29 13
通过执行 df_grouped.index.levels[1]
我发现所有这些中间日期实际上都在索引中,所以也许这是我可以利用的东西.
And by doing df_grouped.index.levels[1]
I see that all those intermediate dates are actually in the index, so maybe that's something I can leverage.
关于如何实现这一目标的任何想法?
Any ideas on how to achieve this?
谢谢
推荐答案
使用 DataFrameGroupBy.resample
和 DatetimeIndex
:
df_grouped = df.set_index('dates').groupby('names').resample('7D').sum()
print (df_grouped)
values
names dates
joe 2019-06-01 7
2019-06-08 0
2019-06-15 0
2019-06-22 0
2019-06-29 13
这篇关于如何使用 7d 频率的 pandas 石斑鱼并用 0 填充缺失的天数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文