首页 > 解决方案 > Python 计数转换并将日期聚合到月份列

问题描述

我有一个数据集,我试图在其中分解并按月计算出现次数。我还需要转换最终结果以添加每个月/发生的列

Report_ID    Report_name    timestamp    
1            Profit         8/1/2018 06:10:40
2            Revenue        8/5/2018 09:25:45
1            Profit         8/29/2018 10:11:30
2            Revenue        9/1/2018  09:45:22

输出:

Report_ID   8/2018    9/2018
1           2         0 
2           1         1

标签: pythonpandascountpandas-groupby

解决方案


pd.crosstab与 dt 访问器一起使用strftime

pd.crosstab(df.Report_ID, df['timestamp'].dt.strftime('%m/%Y'))\
  .reset_index()\
  .rename_axis([None], axis=1)

输出:

   Report_ID  08/2018  09/2018
0          1        2        0
1          2        1        1

推荐阅读