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
这是按宠物和按年分组,并将它们之间的数量相加。
有什么想法吗?
答案 0 :(得分:0)
使用参数as_index=False
的{{3}}不返回MultiIndex
和sort=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