Return the top N rows by value within each group of a pandas DataFrame

Quick Overview

Write a pandas function that returns the n rows with the largest value in each group of a DataFrame, keeping every column, ordering groups and values, and resetting the index. It tests group-wise top-n selection, tie handling and the cost of sorting large frames.

Return the top N rows by value within each group of a pandas DataFrame

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

Implement `top_n_per_group(df, key, val, n)`. Return the `n` rows with the largest `val` within each `key` group, keeping all columns of `df`. ```python import pandas as pd def top_n_per_group(df: pd.DataFrame, key: str, val: str, n: int) -> pd.DataFrame: ... ``` Requirements: - At most `n` rows per distinct `key` (fewer if the group is smaller). - Order groups by `key` ascending, and rows within a group by `val` descending. - Reset the index to a fresh `RangeIndex` starting at 0. Example: ```python df = pd.DataFrame({ "g": ["a", "a", "a", "b", "b"], "v": [10, 30, 20, 5, 7], }) top_n_per_group(df, "g", "v", 2) # g v # 0 a 30 # 1 a 20 # 2 b 7 # 3 b 5 ``` ```hint Order first If the rows were already arranged by group, and by value inside each group, which rows of each group would you need to keep? ``` ```hint Watch the index Filtering rows keeps their original index labels. The required output has a fresh index from 0. ``` ### Constraints & Assumptions - `n >= 0`. - `key` and `val` are columns that exist in `df`. - A group can have fewer than `n` rows. ### Clarifying Questions to Ask - When rows in a group tie on `val` at the nth position, which ones should be kept, and in what order should tied rows appear? - Can `key` or `val` contain missing values, and should those rows appear in the result? - Roughly how many rows and groups are there, and is `n` small compared with a typical group? ### What a Strong Answer Covers - A method that returns at most `n` rows per group with every column of `df` kept. - Output ordered by `key` ascending, then `val` descending within each group. - A fresh 0-based index on the result. - Behavior for ties on `val` and for groups smaller than `n`. - The time complexity, and whether anything beats a full sort in practice. ### Follow-up Questions - How would you break ties deterministically when several rows in a group share the same `val`? - How does this scale, and is there a faster approach than a full sort when `n` is small? - How would you return every row tied with the nth value in each group, even if that gives more than `n` rows?

Overview: Write a pandas function that returns the n rows with the largest value in each group of a DataFrame, keeping every column, ordering groups and values, and resetting the index. It tests group-wise top-n selection, tie handling and the cost of sorting large frames.

General logo
General
Nov 24, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

Implement top_n_per_group(df, key, val, n). Return the n rows with the largest val within each key group, keeping all columns of df.

import pandas as pd


def top_n_per_group(df: pd.DataFrame, key: str, val: str, n: int) -> pd.DataFrame:
    ...

Requirements:

  • At most n rows per distinct key (fewer if the group is smaller).
  • Order groups by key ascending, and rows within a group by val descending.
  • Reset the index to a fresh RangeIndex starting at 0.

Example:

df = pd.DataFrame({
    "g": ["a", "a", "a", "b", "b"],
    "v": [10, 30, 20, 5, 7],
})
top_n_per_group(df, "g", "v", 2)
#    g   v
# 0  a  30
# 1  a  20
# 2  b   7
# 3  b   5

Constraints & Assumptions

  • n >= 0 .
  • key and val are columns that exist in df .
  • A group can have fewer than n rows.

Clarifying Questions to Ask Guidance

  • When rows in a group tie on val at the nth position, which ones should be kept, and in what order should tied rows appear?
  • Can key or val contain missing values, and should those rows appear in the result?
  • Roughly how many rows and groups are there, and is n small compared with a typical group?

What a Strong Answer Covers Guidance

  • A method that returns at most n rows per group with every column of df kept.
  • Output ordered by key ascending, then val descending within each group.
  • A fresh 0-based index on the result.
  • Behavior for ties on val and for groups smaller than n .
  • The time complexity, and whether anything beats a full sort in practice.

Follow-up Questions Guidance

  • How would you break ties deterministically when several rows in a group share the same val ?
  • How does this scale, and is there a faster approach than a full sort when n is small?
  • How would you return every row tied with the nth value in each group, even if that gives more than n rows?