pandas
groupby
max value
data analysis
Python

Get the rows which have the max value in groups using groupby

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

In pandas, "get the rows with the maximum value in each group" is a row-selection problem, not just an aggregation problem. The most common solution is to compute the index of the max row per group and then select those rows from the original DataFrame.

The Standard idxmax Pattern

Use groupby(...)[column].idxmax() when you want one row per group:

python
1import pandas as pd
2
3df = pd.DataFrame({
4    "team": ["A", "A", "B", "B", "C"],
5    "score": [10, 15, 7, 20, 12],
6    "player": ["Ann", "Amy", "Ben", "Bob", "Cam"],
7})
8
9idx = df.groupby("team")["score"].idxmax()
10result = df.loc[idx].sort_values("team")
11
12print(result)

Output:

text
1  team  score player
21    A     15    Amy
33    B     20    Bob
44    C     12    Cam

This is usually the cleanest answer because it returns the full original rows.

Why Plain max() Is Not Enough

If you write:

python
df.groupby("team")["score"].max()

you only get the maximum score per team, not the associated row. That loses the other columns such as player, timestamp, or metadata.

So when you need the whole row, you must connect the max value back to the original frame.

Keeping All Ties

idxmax() returns the first maximum in each group. If ties matter and you want all rows tied for the max, use transform("max"):

python
1max_scores = df.groupby("team")["score"].transform("max")
2result = df[df["score"] == max_scores]
3
4print(result.sort_values(["team", "player"]))

That keeps every row whose score matches the group maximum.

This tie-preserving approach is often the right one for ranking reports or leaderboards, where multiple rows can legitimately share the top value in a group.

Grouping by Multiple Columns

The same idea works for multiple grouping keys:

python
1df = pd.DataFrame({
2    "team": ["A", "A", "A", "B", "B"],
3    "season": [2024, 2024, 2025, 2024, 2024],
4    "score": [10, 15, 12, 7, 20],
5    "player": ["Ann", "Amy", "Ava", "Ben", "Bob"],
6})
7
8idx = df.groupby(["team", "season"])["score"].idxmax()
9result = df.loc[idx]
10
11print(result)

Pandas treats each unique (team, season) pair as its own group.

Sorting Alternative

Another readable method is to sort first and then keep the last or first row in each group:

python
1result = (
2    df.sort_values(["team", "score"])
3      .drop_duplicates("team", keep="last")
4)

This works, but it is usually less direct than idxmax() and makes tie behavior depend on sort order.

It also changes row order unless you deliberately sort the final result back into the layout your downstream code expects.

Handling Missing Values

Be careful with missing scores. idxmax() ignores NaN by default, but a group containing only missing values can behave unexpectedly for row-selection logic. Clean or fill missing values first if needed:

python
df = df.dropna(subset=["score"])

That keeps the selection logic explicit.

If groups may be entirely missing, decide upfront whether they should disappear from the result or be represented separately after preprocessing.

Common Pitfalls

The most common mistake is using groupby().max() and expecting full rows back. That only returns aggregated values.

Another mistake is forgetting that idxmax() keeps only the first tied maximum. Use transform("max") if ties should all remain.

A third issue is applying the logic after resetting or scrambling the index without realizing that loc[idx] selects by index labels, not by row position.

Summary

  • Use groupby(...)[column].idxmax() plus loc to get one max row per group.
  • Use transform("max") when you need all rows tied for the group maximum.
  • 'groupby().max() gives values, not full rows.'
  • The pattern works with one grouping column or many.
  • Watch out for ties and missing values when choosing the selection strategy.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.