Back to Practice
#0136

Top N Rows Per Group

MediumPandas25 min20 XP

Problem

Given a DataFrame with group and score, return the top n rows per group sorted by group then score descending.

Why This Matters

Top-N per group appears in recommendations, leaderboards, best products by category, and model diagnostics.

Function Signature

def top_n_per_group(df, n):

Examples

Example 1
InputA scores 5,9; B scores 2,8; n=1
OutputA 9 and B 8

Each group contributes its own best row.

Constraints

  • Return the exact requested structure.
  • Handle normal edge cases cleanly.
  • Prefer readable code over clever shortcuts.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
InputA scores 5,9; B scores 2,8; n=1
ExpectedA 9 and B 8

Each group contributes its own best row.

Hidden Test Categories
n larger than group sizetiessingle group