Shubham R
Shubham R

Reputation: 7644

groupby 1 column and sum of other columns as new dataframe pandas

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 groupby id and sum other columns such as i get a 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 any better way to do this?

Upvotes: 3

Views: 763

Answers (1)

jezrael
jezrael

Reputation: 863166

Use groupby without define column - aggregate all numeric columns to sum, then add_prefix and 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

Upvotes: 4

Related Questions