Q&A library Python

How do I find the row with the maximum value in pandas?

Python Intermediate groupbyidxmaxmax

Short answer

max gives the value, idxmax gives the index label of the row holding it, so pass idxmax to loc to get the whole row. Combine with groupby to get the top row within each group.

The short version

max() returns the largest value, but usually you want the whole row that holds it. Use idxmax(), which returns the index label of that row, and pass it to .loc. Combined with groupby, idxmax gives you the top row within each group, which is a very common need.

Getting the whole row

import pandas as pd

df = pd.DataFrame({
    "city": ["Leeds", "Leeds", "Bath"],
    "amount": [5, 9, 7],
})

top = df.loc[df["amount"].idxmax()]
print(top)
city      Leeds
amount        9

df["amount"].max() would have given only 9, losing the city. idxmax gives the label of the row containing 9, and .loc fetches the full row.

The top row per group

Pass the result of a grouped idxmax to .loc to get the best row in each group.

best = df.loc[df.groupby("city")["amount"].idxmax()]
print(best)
    city  amount
2   Bath       7
1  Leeds       9

Each city's highest row survives, with all its columns intact. This is much cleaner than sorting and deduplicating, and it makes the intent obvious.

The tie behaviour

If several rows share the maximum, idxmax returns the first one it meets, silently. If ties matter, do not rely on it. Filter on the maximum value instead, which keeps every tied row.

df[df["amount"] == df["amount"].max()]   # keeps all tied rows

Decide deliberately: idxmax when any one of the tied rows will do, and the equality filter when you must keep them all.

The NaN trap

idxmax skips missing values, but if the entire column is NaN it raises. And if you are working with an index that has duplicate labels, .loc with the returned label may fetch more than one row, which is confusing. Reset the index first if your labels are not unique.

nlargest for the top few

For more than one top row overall, nlargest is more direct than sorting the whole frame.

df.nlargest(2, "amount")

This returns the two biggest rows across the frame, not per group, so use it when you want the overall leaders rather than a winner per category.

The minimum equivalents

Everything above has a minimum counterpart: idxmin, min and nsmallest, behaving identically in the other direction.

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project