Overview
From a raw order table, keep the paid orders, compute line totals, add them up per product and rank the products: a real pandas report.
- Filter, compute, group, sort
- .copy() before adding a column
- Returning plain Python data
Short Course
Real analysis chains small steps: filter, add a column, group, sort. Trap: a
filtered DataFrame may be a view of the original; call .copy() before adding
a column to avoid SettingWithCopyWarning.
paid = orders[orders["status"] == "paid"].copy()
paid["total"] = paid["price"] * paid["qty"]
paid.groupby("city")["total"].sum().sort_values(ascending=False).head(2)
Task
Write top_products(df, n) that keeps the paid orders, computes
price * qty, totals it per product and returns the n best products as a
list of (product, revenue) pairs, best first, for example
[('lamp', 120.0), ('mug', 40.0)].
Test Suites
Pending
Next
Output