Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a easy way to do a group by in Python to aggregate a single column

I have a dataframe with fields as follow

field_1 field_2 field_3
A 2 4
B 5 7

I would like aggregate field_2 i.e:

field_1 field_2 field_3 field_2_agg
A 2 4 7
B 5 7 7

I usually create a new dataframe by doing a groupby on the dataframe with the field I want and then merge back the grouped dataframe to the original one. Is there an easier way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this:

df['field_2_agg'] = df['field_2'].sum()

Output:

>>> df
  field_1  field_2  field_3  field_2_agg
0       A        2        4            7
1       B        5        7            7
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading