MaxB
MaxB

Reputation: 458

Find min/max of separate columns after groupby

I have the following dataframe that I want to groupby

TO    FROM    sort    toName    fromName    toLoc    fromLoc      max    min    
 A      B      0       test       test       test      test        10     8
 A      B      0       test       test       test      test        9      2

The idea is to groupby the sort column but preserve the max/min values. The highest max value and the lowest min values are the ones I want to populate.

TO    FROM    sort    toName    fromName    toLoc    fromLoc      max    min    
 A      B      0       test       test       test      test        10     2

I can't figure out how to do the comparison and groupby at the same time, any ideas?

Upvotes: 0

Views: 63

Answers (1)

pissall
pissall

Reputation: 7419

First do the groupby, and then using aggregate, you can get the min and max of two columns:

import numpy as np

agg_dict = {"min": np.min, "max": np.max}
# OR YOU CAN DEFINE IT AS 
agg_dict = {"min": "min", "max": "max"}
df = df.groupby("sort").aggregate(agg_dict)

Upvotes: 1

Related Questions