如何使用Pandas按月和年分组和计算行数?

栏目: 数据库 · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/38792122/how-to-group-and-count-rows-by-month-and-year-using-pandas
我有一个包含姓名,身高,体重和出生日期等个人数据的数据集.我会建立一个图表,显示特定月份和年份出生的人数.我正在使用 python

pandas来实现这一点,我的策略是尝试按年份和月份进行分组并添加使用计数.但我得到的最接近的是按年或按月计算人数,但不是两者.

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

stackoverflow中的其他问题指向一个名为TimeGrouper的Grouper,但在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

UPDATE

从版本 0.23.0 开始,由于多索引级别名称必须唯一的限制,上述代码不再有效,您现在需要重命名级别才能使其工作:

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

翻译自:https://stackoverflow.com/questions/38792122/how-to-group-and-count-rows-by-month-and-year-using-pandas


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Charlotte's Web

Charlotte's Web

E. B. White / Scholastic / 2004 / USD 0.01

This is the tale of how a little girl named Ferm, with the help of a friendly spider, saved her pig, Wilbur, from the usual fate of nice fat little pigs.一起来看看 《Charlotte's Web》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具