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

Groupby() and mean() in pandas dataframe with returning more than two columns

A super simple question, which I cannot find so far.

This is my dataframe

    id  Name    Lastname    Journal     Article   Score
0   1   John    Doo         Journal2    Article1    23
1   2   John    Doo         Journal1    Article2    12
2   3   Bill    Foo         Journal17   Article3    8

When I use

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

df.groupby('id', as_index=False)['Score'].mean()

it gives me

    id  Score
0   1   17.5
1   2   8.0

Expected output

   id   Name Lastname Score
0   1   Joe  Doe      17.5
1   2   Bill Foo      8.0

>Solution :

If same values per id in Name and Lastname columns add it to groupby:

df.groupby(['id','Name','Lastname'], as_index=False)['Score'].mean()

If possible different values per id is possible extract first/last values per groups:

df.groupby('id', as_index=False).agg({'Score':'mean', 'Name':'first', 'Lastname':'first'})

df.groupby('id', as_index=False).agg({'Score':'mean', 'Name':'last', 'Lastname':'last'})
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