How to use pandas Grouper with 7d frequency and fill missing days with 0?

别等时光非礼了梦想. 提交于 2019-12-08 03:52:35

问题


I have the following sample dataset

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]
})

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

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?

Thanks


回答1:


Use DataFrameGroupBy.resample with 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


来源:https://stackoverflow.com/questions/57323065/how-to-use-pandas-grouper-with-7d-frequency-and-fill-missing-days-with-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!