python - groupby 1 column and sum of other columns as new dataframe pandas -
i have 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 groupby id , sum other columns such df
id total_won total_lost total_match v1 3 6 12 v2 8 6 19 how can use pandas groupby , sum operation sum multiple columns. tried using this:
pd.groupby('id')['won'].sum() pd.groupby('id')['lost'].sum() pd.groupby('id')['match'].sum() is there better way this?
use groupby without define column - aggregate numeric columns sum, add_prefix , last 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 need specify multiple columns, add list of 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
Comments
Post a Comment