Python计数转换并将日期聚合到月份列
我有一个数据集,在那里我试图按月份细分和统计发生的次数。我还需要转换最终结果,为每个月/事件添加一列Python计数转换并将日期聚合到月份列,python,pandas,count,pandas-groupby,Python,Pandas,Count,Pandas Groupby,我有一个数据集,在那里我试图按月份细分和统计发生的次数。我还需要转换最终结果,为每个月/事件添加一列 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 Reven
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
Report_ID 08/2018 09/2018
0 1 2 0
1 2 1 1
通过dt存取器使用
strftime
,使用pd.crosstab
:
pd.crosstab(df.Report_ID, df['timestamp'].dt.strftime('%m/%Y'))\
.reset_index()\
.rename_axis([None], axis=1)
输出:
Report_ID 8/2018 9/2018
1 2 0
2 1 1
Report_ID 08/2018 09/2018
0 1 2 0
1 2 1 1
您的数据是
pandas
dataframe还是其他格式?它将从.xlsx文件中输入,然后通过pd.read_excel()@Scott读入python,这非常有效!非常感谢你!一个快速的跟进,我的数据集有生命到目前为止(12个月以上)的数据。如何将交叉表数据框限制为最后3个月?创建一个仅包含最后3个月数据的新数据框,然后使用相同的命令。