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.
- Pick a CSV with at least one category column and one numeric column you can sort by.
- Sort the whole DataFrame by the numeric column, descending.
- Group by the category column and print the first five rows of each group.
- 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 printHow we'll grade it
Four checks, four points. Three or above is passing — we'll ask you to revise anything we can't tick.
| Check | What we look for | Pt |
|---|---|---|
| It runs | End to end on a fresh notebook with pandas installed. | 1 |
| Sort works | The DataFrame is ordered by the numeric column before grouping. | 1 |
| Top 5 per group | Each group's first five rows are correct, not just a single five. | 1 |
| Finding is real | Your one-sentence summary is backed by what's on the screen. | 1 |