python - Best Way to add group totals to a dataframe in Pandas -


i have simple task i'm wondering if there better / more efficient way do. have dataframe looks this:

  group  score  count 0          5    100 1          1     50 2          3      5 3     b      1     40 4     b      2     20 5     b      1     60 

and want add column holds value of group total count:

  group  score  count  totalcount 0          5    100         155 1          1     50         155 2          3      5         155 3     b      1     40         120 4     b      2     20         120 5     b      1     60         120 

the way did was:

grouped=df.groupby('group')['count'].sum().reset_index() grouped=grouped.rename(columns={'count':'totalcount'})  df=pd.merge(df, grouped, on='group', how='left') 

is there better / cleaner way add these values directly dataframe?

thanks help.

df['totalcount'] = df.groupby('group')['count'].transform(sum) 

some other options discussed here.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -