简体   繁体   English

Groupby 2 个不同的列 Python Pandas

[英]Groupby 2 different columns 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 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

I would like to turn the above dataframe into the following:我想将上面的数据框变成以下内容:

DF2 DF2

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

This is grouping by Pet and by Year and summing the amount between them.这是按宠物和按年份分组,并汇总它们之间的数量。

Any ideas?有任何想法吗?

Use groupby with parameters as_index=False for not return MultiIndex and sort=False for avoid sorting:使用带参数as_index=False groupby不返回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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM