wk03.p3Practice exerciseWeek 03 · Data and the outside worldOpen · due in week 3

Top five rows per category

Take a CSV, group it by a category column, and pull out the top five rows from each group. Pandas at its most useful.

What you'll build

Take a CSV, group it by a category column, and pull out the top five rows from each group. Pandas at its most useful.

Requirements

The must-do parts. If any are missing, we'll ask you to take another pass.

  1. Pick a CSV with at least one category column and one numeric column you can sort by.
  2. Sort the whole DataFrame by the numeric column, descending.
  3. Group by the category column and print the first five rows of each group.
  4. Print a single short sentence summarizing what you found in the leader of each group.
Bonus, if you're feeling brave
  • Save the result to a new CSV with to_csv("top5.csv", index=False).
  • Plot a bar chart of the top one per category.

Where to start

Copy this scaffold into a new file. You don't have to use it — it's just a friendly nudge.

top_by_category.py
import pandas as pd

df = pd.read_csv("your-file.csv")

# 1. Sort by the numeric column, descending
df_sorted = df.sort_values("numeric_column", ascending=False)

# 2. Group by category and take the head of each group
top5 = df_sorted.groupby("category_column").head(5)

# 3. Print it nicely
print(top5)

# 4. Add a one-sentence summary as a comment or print

How we'll grade it

Four checks, four points. Three or above is passing — we'll ask you to revise anything we can't tick.

CheckWhat we look forPt
It runsEnd to end on a fresh notebook with pandas installed.1
Sort worksThe DataFrame is ordered by the numeric column before grouping.1
Top 5 per groupEach group's first five rows are correct, not just a single five.1
Finding is realYour one-sentence summary is backed by what's on the screen.1
Ready?
Hand it in
You can submit a draft and revise later if you're not done.
Begin submission →