以下是我的数据示例:
Date Count
11.01.2019 1
01.02.2019 7
25.01.2019 4
23.01.2019 4
16.03.2019 1
04.02.2019 5
06.04.2019 1
04.04.2019 5
所需输出:
Month Total_Count
Jan 9
Feb 12
Mar 1
Apr 6
对于上面的总结操作,我使用了下面的代码,它工作得很好,但是月份都很混乱,没有像一月、二月那样进行相应的排序
(df.groupby(pd.to_datetime(df['Date'], format='%d.%m.%Y')
.dt.month_name()
.str[:3])['Count']
.sum()
.rename_axis('Month')
.reset_index(name='Total_Count'))
想法是将列转换为日期时间,然后使用
sort=False
进行排序和分组,以避免groupby
中的默认排序:另一个想法是,谢谢anky,使用有序的
Categorical
,然后需要删除sort=False
:或使用^{} :
试试这个:
相关问题 更多 >
编程相关推荐