Quang Minh Vu
Quang Minh Vu

Reputation: 17

Get row which has max value in each group using python pandas

I have a dataframe. It is group by 'ex' as below: enter image description here Now I want to get rows which have max value in each group

Upvotes: -1

Views: 2040

Answers (2)

shai gindin
shai gindin

Reputation: 127

A quick google search and you will find out how to get relevant rows here. For your implementation:

df.groupby("ex")['transaction_fee'].max()

The other thing you should look for is how to get the corresponding indices for the original table. you could find something similar here. For your implementation:

idxs = df.groupby("ex")['transaction_fee'].transform(max) == df['transaction_fee']
relevant_df = df[idxs]

Upvotes: 2

Gags08
Gags08

Reputation: 252

For getting all the column values for a group by of one column and max value of another column. Use idxmax() and iloc()

idxmax() will return the index of the maximum value, not the maximum value itself.

iloc() Index based, returns the selected section of df.
We can use the ids to filter the records.

idxs = df.groupby("ex")['transaction_fee'].idxmax()
df = df.iloc[idxs]

Upvotes: 0

Related Questions