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

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

内容简介:翻译自: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


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

查看所有标签

猜你喜欢:

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

Mastering JavaServer Faces

Mastering JavaServer Faces

Bill Dudney、Jonathan Lehr、Bill Willis、LeRoy Mattingly / Wiley / 2004-6-7 / USD 40.00

Harness the power of JavaServer Faces to create your own server-side user interfaces for the Web This innovative book arms you with the tools to utilize JavaServer Faces (JSF), a new standard that wi......一起来看看 《Mastering JavaServer Faces》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

MD5 加密
MD5 加密

MD5 加密工具