en utilisant l'exemple de Pandas somme par groupby, mais en excluant certaines colonnes
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
quand on fait le
df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum()
la sortie sera
Y1961 Y1962 Y1963
Country Item_Code
Afghanistan 15 10 20 30
25 10 20 30
Angola 15 30 40 50
25 30 40 50
Maintenant, voici mes questions
quand je le ferai, df.columns
je n'obtiendrai queY1961 Y1962 Y1963
Mais que faire si je veux Country, Item_Code
être inclus sous forme de colonnes comme ci-dessous
df.columns
Country, Item_Code ,Y1961 Y1962 Y1963
vous devez spécifier l'argument 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')
tu pourrais aussi faire
df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum().reset_index()
Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.
En caso de infracción, por favor [email protected] Eliminar
Déjame decir algunas palabras