且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-20 17:00:20

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

To group on multiple criteria, pass a list of the columns or criteria:

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级别才能起作用:

As of version 0.23.0 the above code no longer works due to the restriction that multi-index level names must be unique, you now need to rename the levels in order for this to work:

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