Groupby 1 column and sum of other columns as new pandas dataframe
I have a pandas dataframe:
id won lost match
v1 1 0 1
v1 2 1 3
v1 0 5 8
v2 3 1 7
v2 5 5 12
I want to group id and sum other columns like I get df
id total_won total_lost total_match
v1 3 6 12
v2 8 6 19
How can I use pandas groupby and sum operation to sum multiple columns. I tried using this:
pd.groupby('id')['won'].sum()
pd.groupby('id')['lost'].sum()
pd.groupby('id')['match'].sum()
Is there a better way to do this?
+3
source to share
1 answer
Use groupby
without column definition - aggregate all numeric columns into a sum, then the add_prefix
last one reset_index
:
df1 = df.groupby('id').sum().add_prefix('total_').reset_index()
print (df1)
id total_won total_lost total_match
0 v1 3 6 12
1 v2 8 6 19
If you need to specify multiple columns, add list
columns:
cols = ['won','lost']
df1 = df.groupby('id')[cols].sum().add_prefix('total_').reset_index()
print (df1)
id total_won total_lost
0 v1 3 6
1 v2 8 6
+4
source to share