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

grouping dataframe by column with condition

there is my dataframe :

df = pd.DataFrame({
'name':["aa","aa","aa","bb","cc","cc"],
'value':[1,2,3,4,5,6]})

I would like grouping by ‘name’ and values sum . Only ‘name’ column items having more than one occurence are selected . the new dataframe will contain 2 columns ‘name’ and ‘total’

Desired output :

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

enter image description here

I tried this :
(df[df.groupby([‘name’]).count() > 1].groupby([‘name’])[‘value’].sum())
but didn’t work . I got an error

Would be great to get a hint – Thanks

>Solution :

Code

make condition using transform & aggregate

cond = df.groupby('name')['value'].transform('count') > 1
out = df[cond].groupby('name')['value'].sum().reset_index(name='total')

out

    name    total
0   aa      6
1   cc      11
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