pandas 数据框按多列分组 [英] Pandas dataframe group by multiple columns
本文介绍了 pandas 数据框按多列分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个具有两个日期时间列A
和B
和一个数值列C
的数据框,如何将A
和B
和sum(C)
的month
分组,即
Given a dataframe with two datetime columns A
and B
and a numeric column C
, how to group by month
of both A
and B
and sum(C)
i.e.
In [1]: df
Out[1]:
A B C
0 2013-01-01 2013-01-01 0.282863
1 2013-01-02 2013-01-01 0.173215
2 2013-02-03 2013-02-04 2.104569
3 2013-02-09 2013-04-15 0.706771
4 2013-03-05 2013-08-01 0.567020
5 2013-03-06 2013-04-01 0.113648
推荐答案
通过使用groupby
df.groupby([df.A.dt.month,df.B.dt.month]).C.sum()
Out[954]:
A B
1 1 0.456078
2 2 2.104569
4 0.706771
3 4 0.113648
8 0.567020
Name: C, dtype: float64
注意:通过使用此命令,请确保A和B为日期时间格式,否则,请在groupby
Note: By using this , make sure A and B are datetime format If not , do following code before groupby
df.A=pd.to_datetime(df.A)
df.B=pd.to_datetime(df.B)
这篇关于 pandas 数据框按多列分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文