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

Python: Groupby and sum respective rows and update dataframe column

Input df:

Store   Category    Item    tot_table
11      AA          Apple   13.5
11      AA          Orange  13.5
11      BB          Potato  11.5
11      BB          Carrot  11.5
12      AA          Apple   10  
12      BB          Potato  9
12      BB          Carrot  9

Need to perform df.groupby('Store')['tot_table'].unique().sum() , but this line of code doesn’t work out.

Expected output df:

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

Store   Category    Item    split_table     tot_table
11      AA          Apple   13.5                25
11      AA          Orange  13.5                25
11      BB          Potato  11.5                25
11      BB          Carrot  11.5                25
12      AA          Apple   10                  19
12      BB          Potato  9                   19
12      BB          Carrot  9                   19

>Solution :

You can use groupby.transform with unique/sum:

df['tot_table'] = (df.groupby('Store')['tot_table']
                     .transform(lambda s: s.unique().sum())
                  )

output:

   Store Category    Item  tot_table
0     11       AA   Apple       25.0
1     11       AA  Orange       25.0
2     11       BB  Potato       25.0
3     11       BB  Carrot       25.0
4     12       AA   Apple       19.0
5     12       BB  Potato       19.0
6     12       BB  Carrot       19.0
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