如何使用pandas按月和年对行进行分组和计数?

如何使用pandas按月和年对行进行分组和计数?,第1张

如何使用pandas按月和年对行进行分组和计数?

要对多个条件进行分组,请传递列或条件的列表:

df['birthdate'].groupby([df.birthdate.dt.year, df.birthdate.dt.month]).agg('count')

例:

In [165]:df = pd.Dataframe({'birthdate':pd.date_range(start=dt.datetime(2015,12,20),end=dt.datetime(2016,3,1))})df.groupby([df['birthdate'].dt.year, df['birthdate'].dt.month]).agg({'count'})Out[165]:         birthdate  countbirthdate birthdate          2015      12    122016      1     31          2     29          3      1

更新

由于

0.23.0
多索引级别名称必须唯一的限制,上述代码从版本开始不再起作用,您现在需要
rename
级别才能使其起作用:

In[107]:df.groupby([df['birthdate'].dt.year.rename('year'), df['birthdate'].dt.month.rename('month')]).agg({'count'})Out[107]: birthdate    countyear month          2015 12122016 1 31     2 29     3  1


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5667050.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存