我有一个包含姓名,身高,体重和出生日期等个人数据的数据集.我会建立一个图表,显示特定月份和年份出生的人数.我正在使用python pandas来完成这个,我的策略是尝试按年份和月份进行分组并添加使用计数.但我得到的最接近的是按年或按月计算人数,但不是两者.
df['birthdate'].groupby(df.birthdate.dt.year).agg('count')
Run Code Online (Sandbox Code Playgroud)
stackoverflow中的其他问题指向一个名为TimeGrouper的Grouper,但在pandas文档中搜索没有发现任何问题.任何的想法?
EdC*_*ica 28
要对多个条件进行分组,请传递列或列表的列表:
df['birthdate'].groupby([df.birthdate.dt.year, df.birthdate.dt.month]).agg('count')
Run Code Online (Sandbox Code Playgroud)
例:
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
Run Code Online (Sandbox Code Playgroud)
UPDATE
从版本开始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
Run Code Online (Sandbox Code Playgroud)
And*_*den 14
您还可以将"月"期与访问者一起to_period
使用dt
:
In [11]: df = pd.DataFrame({'birthdate': pd.date_range(start='20-12-2015', end='3-1-2016')})
In [12]: df['birthdate'].groupby(df.birthdate.dt.to_period("M")).agg('count')
Out[12]:
birthdate
2015-12 12
2016-01 31
2016-02 29
2016-03 1
Freq: M, Name: birthdate, dtype: int64
Run Code Online (Sandbox Code Playgroud)
值得注意的是,日期时间是否可以使用的索引(而不是列)resample
:
df.resample("M").count()
Run Code Online (Sandbox Code Playgroud)
另一个解决方案是设置birthdate
为索引并重新采样:
import pandas as pd
df = pd.DataFrame({'birthdate': pd.date_range(start='20-12-2015', end='3-1-2016')})
df.set_index('birthdate').resample('MS').size()
Run Code Online (Sandbox Code Playgroud)
输出:
birthdate
2015-12-01 12
2016-01-01 31
2016-02-01 29
2016-03-01 1
Freq: MS, dtype: int64
Run Code Online (Sandbox Code Playgroud)