Find maximum value of a column and return the corresponding row values using Pandas
Assuming df
has a unique index, this gives the row with the maximum value:
In [34]: df.loc[df['Value'].idxmax()]
Out[34]:
Country US
Place Kansas
Value 894
Name: 7
Note that idxmax
returns index labels. So if the DataFrame has duplicates in the index, the label may not uniquely identify the row, so df.loc
may return more than one row.
Therefore, if df
does not have a unique index, you must make the index unique before proceeding as above. Depending on the DataFrame, sometimes you can use stack
or set_index
to make the index unique. Or, you can simply reset the index (so the rows become renumbered, starting at 0):
df = df.reset_index()
df[df['Value']==df['Value'].max()]
This will return the entire row with max value
The country and place is the index of the series, if you don't need the index, you can set as_index=False
:
df.groupby(['country','place'], as_index=False)['value'].max()
Edit:
It seems that you want the place with max value for every country, following code will do what you want:
df.groupby("country").apply(lambda df:df.irow(df.value.argmax()))