Warren Manuel
Warren Manuel

Reputation: 51

Extracting the group that has a specific groupby aggregate value in Pandas

I'm doing a pandas groupby for a specific DataFrame which looks like this

Group Value
A 1
A 2
B 2
B 3

And when I apply df.groupby('Group')['Value'].mean() I get

Group
A 1.5
B 2.5
Name: Value, dtype: float64

My end result is trying to find the group that has the max groupby aggregation (ie: Group B) as my result

I understand that groups.keys() is an option to list the keys but would there be a way to repeatedly get the groupname for a specific aggregation. ?

Thanks !

Upvotes: 2

Views: 39

Answers (1)

mozway
mozway

Reputation: 260745

By default, groupby sets your grouping column as index of the aggregation. Use idxmax:

df.groupby('Group')['Value'].mean().idxmax()

Output: 'B'

Upvotes: 2

Related Questions