Home > Software engineering >  How to create a new column that contains the sum of all the revenues for a particular Account ID
How to create a new column that contains the sum of all the revenues for a particular Account ID

Time:02-02

df has the following cols, df['Account ID'] and df['Revenue']. df['Account ID'] has duplicate values. Tried the following but it generates empty col:

df['Total_Revenue'] = df.groupby('Account ID')['Revenue'].sum()col views in excel

thanks for the help.

CodePudding user response:

Use assign method to create new column then groupby transform to not collapse the aggregation.

Code:

df.assign(total_revenue=lambda df_: df_.groupby("Account ID").Revenue.transform("sum"))

Documentation:

  • Related