您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

如何使用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
                        count
birthdate birthdate          
2015      12               12
2016      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
               count
year month          
2015 12           12
2016 1            31
     2            29
     3             1
其他 2022/1/1 18:28:45 有481人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶