Groupby 2个不同的列Python Pandas

时间:2017-01-10 19:38:58

标签: python pandas

import pandas as pd

df1 = pd.DataFrame([['Dog', '2017', 100], ['Dog', '2017' ,500],['Dog', '2016' ,200],['Dog', '2016' ,150],['Cat', '2017' ,50],['Cat', '2017' ,100],
['Cat', '2016' ,50]], columns=('Pet','Year','Amount'))

DF1

Pet  Year  Amount
Dog  2017  100
Dog  2017  500
Dog  2016  200
Dog  2016  150
Cat  2017  50
Cat  2017  100
Cat  2016  50

我想将上述数据框转换为以下内容:

DF2

Pet Year Amount
Dog 2017 600
Dog 2016 350
Cat 2017 150
Cat 2016 50

这是按宠物和按年分组,并将它们之间的数量相加。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

使用参数as_index=False的{​​{3}}不返回MultiIndexsort=False以避免排序:

print (df1.groupby(['Pet','Year'], as_index=False, sort=False).sum())
   Pet  Year  Amount
0  Dog  2017     600
1  Dog  2016     350
2  Cat  2017     150
3  Cat  2016      50