使用来自groupby的熊猫总和示例,但排除某些列
Code Country Item_Code Item Ele_Code Unit Y1961 Y1962 Y1963
2 Afghanistan 15 Wheat 5312 Ha 10 20 30
2 Afghanistan 25 Maize 5312 Ha 10 20 30
4 Angola 15 Wheat 7312 Ha 30 40 50
4 Angola 25 Maize 7312 Ha 30 40 50
当我们做
df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum()
输出将是
Y1961 Y1962 Y1963
Country Item_Code
Afghanistan 15 10 20 30
25 10 20 30
Angola 15 30 40 50
25 30 40 50
现在,这是我的问题
当我做的时候我df.columns
只会Y1961 Y1962 Y1963
但是,如果需要的话,Country, Item_Code
将包含在下面的列中
df.columns
Country, Item_Code ,Y1961 Y1962 Y1963
您需要指定arg as_index=False
df.groupby(['Country', 'Item_Code'],as_index=False)[["Y1961", "Y1962", "Y1963"]].sum()
Country Item_Code Y1961 Y1962 Y1963
0 Afghanistan 15 10 20 30
1 Afghanistan 25 10 20 30
2 Angola 15 30 40 50
3 Angola 25 30 40 50
df.columns
Index(['Code', 'Country', 'Item_Code', 'Item', 'Ele_Code', 'Unit', 'Y1961',
'Y1962', 'Y1963'],
dtype='object')
你也可以
df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum().reset_index()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句