pandas
DataFrame
Python
data analysis
maximum value

Find row where values for column is maximal in a pandas DataFrame

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Selecting the row with the maximum value in a pandas column is a common data-analysis task, but the right method depends on tie handling, missing values, and index semantics. A clean solution starts by deciding whether you want one winning row, all tied rows, or grouped maxima per category.

Use idxmax When One Winner Is Enough

If returning the first maximum row is acceptable, idxmax is usually the simplest choice. It gives you the index label of the maximum value, which you can then pass to loc.

python
1import pandas as pd
2
3df = pd.DataFrame(
4    {
5        "name": ["a", "b", "c", "d"],
6        "score": [10, 40, 40, 25],
7    }
8)
9
10idx = df["score"].idxmax()
11row = df.loc[idx]
12
13print(idx)
14print(row)

This is concise and fast, but it intentionally returns only the first matching maximum. If ties matter, it is the wrong tool by itself.

Return All Tied Maximum Rows

For leaderboard-style results or fairness-sensitive reporting, compute the maximum once and filter all rows that match it.

python
1max_score = df["score"].max()
2winners = df[df["score"] == max_score]
3
4print(winners)

This makes the semantics explicit. Every row tied for the highest value is preserved, and you avoid the hidden “first row wins” rule of idxmax.

Handle Missing Values Explicitly

Columns with all missing values or mixed missing and numeric values need care. If you call idxmax blindly on a column with no valid numbers, the result may be misleading or raise an error depending on the exact state.

python
1if df["score"].notna().any():
2    idx = df["score"].idxmax()
3    print(df.loc[idx])
4else:
5    print("No valid score values")

This check is cheap and keeps edge-case behavior clear. If your pipeline treats missing scores as invalid input, raising an error may be better than printing a fallback message.

Grouped Maxima by Category

Many real tasks need the maximum row per group rather than across the whole DataFrame. In that case, combine groupby with idxmax.

python
1df2 = pd.DataFrame(
2    {
3        "team": ["x", "x", "y", "y"],
4        "player": ["p1", "p2", "p3", "p4"],
5        "score": [5, 9, 4, 11],
6    }
7)
8
9idx = df2.groupby("team")["score"].idxmax()
10result = df2.loc[idx].sort_values("team")
11
12print(result)

This returns one row per group and follows the same first-maximum behavior inside each group.

Preserve Ties Within Groups

If grouped ties should all be returned, use transform("max") to compute each group’s maximum and then filter.

python
1group_max = df2.groupby("team")["score"].transform("max")
2all_group_winners = df2[df2["score"] == group_max]
3
4print(all_group_winners.sort_values(["team", "player"]))

This pattern is often more aligned with business logic than idxmax, especially when equal top performers should not be dropped.

Define Tie-Breaking Rules When Only One Row May Win

Sometimes you must return one row even when several share the same maximum value. In that case, make the tie-break rule visible in the code by sorting on secondary columns.

python
1winner = (
2    df.sort_values(["score", "name"], ascending=[False, True])
3      .head(1)
4)
5
6print(winner)

This is more maintainable than depending on current row order, which may change after a merge, sort, or file import.

Keep Index Semantics Straight

idxmax returns an index label, not necessarily a positional integer. That means loc is usually correct, while iloc can be wrong if the DataFrame has a custom index.

python
df.index = [101, 102, 103, 104]
idx = df["score"].idxmax()
print(df.loc[idx])

Confusing labels and positions is one of the most common bugs in row selection code.

Common Pitfalls

The biggest mistake is using idxmax when the real requirement is to keep all tied maxima. Another is ignoring missing values and assuming the target column always contains a valid numeric winner. Developers also mix up loc and iloc, which works accidentally on default integer indices and then breaks once the index changes.

Summary

  • Use idxmax when one maximum row is sufficient and first-tie wins is acceptable.
  • Filter by df[col] == df[col].max() when all maximum rows should be returned.
  • Add explicit handling for missing values before selecting the winner.
  • Use groupby patterns for per-group maxima and choose tie behavior intentionally.
  • Treat the result of idxmax as an index label and access rows with loc.

Course illustration
Course illustration

All Rights Reserved.