Skip to content

Using groupby on already grouped data in pandas

I would like to achieve the below in python using pandas. enter image description here

I tried groupby and sum on id and Group columns using the below: df.groupby([‘id’,’Group’])[‘Total’].sum()

I got the first two columns, but I’m not sure on how to get the third column (Overall_Total).

Any suggestions would be helpful.

Thank you


  • EDIT:


Adding Initial data (before grouping) enter image description here



Assuming df is your initial dataframe, please try this:

df_group = df.groupby(['id','group']).sum(['time']).rename(columns={'time':'Total'})
df_group['All_total'] = df_group.groupby(['id'])['Total'].transform('sum')
6 People found this is helpful