25. pandas advanced — Mini-project
Every month, the four regional managers meet to review their stores. Today, an analyst builds their scorecard by hand: a spreadsheet export, three lookups and a pivot table. It takes half a day, and last month a duplicated row in the store list doubled one store’s numbers.
Write a script, scorecard.py, that builds the scorecard in one run from the raw tables. For each store and month, it reports revenue, orders, average order value, gross margin, revenue per square meter, the store’s share of its region, its rank in the region, a 3-month rolling revenue and the change from the previous month. It also prints a quarterly revenue table for 2024 and saves the 2024 scorecard as a CSV file for the managers.
The project uses every part of module 25: compact dtypes, validated merges, method chains with pipe and assign, named aggregation, transform and group ranks, rolling windows within groups, the .dt accessor, a pivot table with margins and checks that the numbers add up.
Dataset
Section titled “Dataset”Three course tables (see Get the data):
| File | Rows | Columns this project needs |
|---|---|---|
data/sales.csv |
20,228 | order_id, order_date, store_id, region, product_id, quantity, revenue |
data/stores.csv |
12 | store_id, city, size_sqm |
data/products.csv |
30 | product_id, unit_cost |
The sales run from 2023-01-01 to 2024-12-31. Store S12 (Denver) opened on 2023-06-15, so it has no rows before June 2023. Gross profit per line is revenue - unit_cost * quantity.
Requirements
Section titled “Requirements”Your script must:
- Read
data/sales.csvwith compact dtypes set at load time:categoryfor the six low-cardinality text columns andint8forquantity. Print the number of rows and the memory in MB. - Attach
city,size_sqmandunit_costwith two left merges. Validate both as many-to-one and assert that the row count does not change. - Build one row per store and month (
region,store_id,city,month) with named aggregation:revenue,orders(distinct orders),profitandsize_sqm. - Add these columns without loops over rows:
aov(revenue per order),margin(profit / revenue) andper_sqm(revenue per m²);region_share: the store’s share of its region’s revenue in that month;region_rank: 1 for the store with the most revenue in its region that month;rolling_3m: the mean revenue of the store’s last 3 months (fewer at the start);mom: the change in revenue from the store’s previous month, as a fraction.
- Write the steps as functions with type hints and join them with
pipe. - Print the December 2024 scorecard, sorted by region and rank, with the columns
region,store_id,city,revenue,aov,margin,region_share,region_rankandmom, rounded to 3 decimals. - Print S12’s last four months of 2024 with
monthas the index and the columnsrevenue,per_sqm,rolling_3mandmom, rounded to 3 decimals. This shows that the trends stay within one store. - Print a 2024 revenue table in thousands of USD: one row per store, one column per quarter, with totals.
- Save the 2024 scorecard to
output/store_scorecard_2024.csv. - End with
assertchecks: the scorecard revenue equals the sales revenue; the region shares of each month add up to 1; 2024 has 12 stores × 12 months; a store’s firstrolling_3mequals its first revenue, and its thirdrolling_3mis the mean of its first three months.
The expected report:
sales: 20228 rows, 1.38 MB(283, 15) (144, 15)region store_id city revenue aov margin region_share region_rank mom East S07 New York 43967.33 244.263 0.466 0.495 1 0.115 East S08 Boston 27803.58 269.938 0.453 0.313 2 0.440 East S09 Philadelphia 17099.27 244.275 0.444 0.192 3 -0.219 North S01 Chicago 40404.83 264.084 0.458 0.514 1 0.525 North S02 Minneapolis 23064.73 240.258 0.468 0.293 2 0.089 North S03 Detroit 15160.59 248.534 0.480 0.193 3 0.269 South S04 Houston 31485.30 264.582 0.468 0.445 1 0.042 South S05 Atlanta 23225.83 219.112 0.493 0.328 2 0.367 South S06 Miami 16074.08 203.469 0.495 0.227 3 -0.252 West S10 Seattle 29547.86 256.938 0.452 0.457 1 0.161 West S11 San Francisco 23765.22 228.512 0.480 0.368 2 0.112 West S12 Denver 11313.15 221.826 0.493 0.175 3 -0.106 revenue per_sqm rolling_3m mommonth2024-09 5348.64 3.962 5515.143 -0.1372024-10 9840.72 7.289 7128.067 0.8402024-11 12647.68 9.369 9279.013 0.2852024-12 11313.15 8.380 11267.183 -0.106quarter 1 2 3 4 Totalstore_idS01 40.7 45.4 52.5 82.4 220.9S02 21.9 27.8 33.1 58.8 141.6S03 16.7 34.9 24.7 38.9 115.2S04 33.8 48.6 47.4 81.0 210.7S05 32.4 31.8 38.5 57.5 160.2S06 23.1 15.0 27.5 45.7 111.4S07 44.9 50.2 62.5 106.2 263.9S08 31.1 32.1 29.5 55.6 148.4S09 23.8 29.0 32.6 47.1 132.5S10 45.6 40.6 49.3 77.7 213.2S11 30.9 29.0 28.4 52.8 141.2S12 26.4 15.0 16.5 33.8 91.8Total 371.5 399.5 442.4 737.5 1950.9saved: output/store_scorecard_2024.csv (144 rows)The second line shows the full scorecard (2023 and 2024) and the 2024 part. 12 stores × 24 months would be 288 rows; S12 has no rows for its 5 months before opening, so the full scorecard has 283.
Step plan
Section titled “Step plan”-
Load with compact dtypes. Write
load_sales(path). Build the dtype dict with a dict comprehension for the six text columns and add"quantity": "int8"with|. Print the memory withmemory_usage(deep=True).sum(). -
Merge the dimensions. Write
add_dimensions(sales, stores, products). Select only the columns you need from each dimension table, merge withhow="left"andvalidate="many_to_one", and assert the length. Cast the dimension keys tocategoryfirst, so that both sides of each merge have the same dtype. -
Aggregate per store and month. In
monthly_scorecard(lines), addmonthwith.dt.to_period("M")andprofitwithassign, then group by region, store, city and month.observed=Trueis the pandas 3 default: with categorical keys, only the combinations that exist appear. Pass it explicitly so that the script behaves the same on pandas 2. -
Add the ratios.
aov,marginandper_sqmare column divisions after the aggregation. -
Add the group columns. Group by
["region", "month"]for the share (transform("sum")) and the rank (rank(ascending=False, method="min"), which gives whole numbers even for ties). Sort by store and month, then group bystore_idforrolling_3mandmom(pct_change()). -
Report. Filter 2024 with
.dt.yearon the period column. Select December withpd.Period("2024-12", "M"). Useto_string(index=False)for the scorecard. Build the quarterly table withpivot_table(..., margins=True, margins_name="Total")and.div(1000).round(1). -
Save and check. Create
output/withPath.mkdir(exist_ok=True), write the CSV withindex=Falseand add the asserts. -
Run it with
python scorecard.pyand compare every line with the expected report.
A skeleton to start from:
# scorecard.py: a monthly store scorecard for 2024 from three course tables.from pathlib import Path
import pandas as pd
def load_sales(path: str = "data/sales.csv") -> pd.DataFrame: """Read the sales lines with compact dtypes.""" # TODO: category for six text columns, int8 for quantity
def add_dimensions( sales: pd.DataFrame, stores: pd.DataFrame, products: pd.DataFrame) -> pd.DataFrame: """Attach city, floor area and unit cost; every merge is many-to-one.""" # TODO: two validated left merges and a length check
def monthly_scorecard(lines: pd.DataFrame) -> pd.DataFrame: """One row per store and month with KPIs, shares, ranks and trends.""" # TODO: assign month and profit, groupby + named agg, then the derived columns
# TODO: load, pipe, print the reports, save the CSV, assertRubric
Section titled “Rubric”| Criterion | Points | Full points when |
|---|---|---|
| Runs as a script | 2 | python scorecard.py runs with no error and no warning |
| Correct numbers | 3 | Every line matches the expected report |
| Compact loading | 2 | dtypes set in read_csv; memory printed |
| Safe merges | 2 | Both merges use validate="many_to_one"; the row count is checked |
| Group logic | 3 | Named aggregation; shares with transform; ranks within region and month; rolling and pct_change within each store |
| Reshaping | 1 | The quarterly table comes from pivot_table with margins |
| Readable code | 2 | Typed functions joined with pipe; one step per line in chains; no row loops |
| Self-checks | 1 | The three required asserts |
| Total | 16 | 13 or more: you are ready for module 26 |
Stretch goals
Section titled “Stretch goals”- Add a
yoycolumn: the change from the same month one year earlier. Usegroupby("store_id")["revenue"].shift(12)and explain why S12 has NaN until mid-2024. - Flag “watch” stores: a negative
momfor two months in a row. Useshift(1)within each store. - Add an
online_sharecolumn per store and month. Compute it before the aggregation withwhere, as in lesson Example 1. - Write the scorecard to Parquet as well, and compare the file sizes and the dtypes after reading both files back.
- Turn the script into a command-line tool with
argparse(module 08) that takes the month to report, such as--month 2024-11.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare your script with this one. Your names and the order of your columns can differ; your printed numbers must not.
Reference solution
# scorecard.py: a monthly store scorecard for 2024 from three course tables.from pathlib import Path
import pandas as pd
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
TEXT_COLUMNS = ["store_id", "region", "channel", "product_id", "product", "category"]REPORT_COLUMNS = [ "region", "store_id", "city", "revenue", "aov", "margin", "region_share", "region_rank", "mom",]
def load_sales(path: str = "data/sales.csv") -> pd.DataFrame: """Read the sales lines with compact dtypes.""" dtypes = {col: "category" for col in TEXT_COLUMNS} | {"quantity": "int8"} return pd.read_csv(path, parse_dates=["order_date"], dtype=dtypes)
def add_dimensions( sales: pd.DataFrame, stores: pd.DataFrame, products: pd.DataFrame) -> pd.DataFrame: """Attach city, floor area and unit cost; every merge is many-to-one.""" stores = stores.astype({"store_id": "category"}) products = products.astype({"product_id": "category"}) out = sales.merge( stores[["store_id", "city", "size_sqm"]], on="store_id", how="left", validate="many_to_one", ).merge( products[["product_id", "unit_cost"]], on="product_id", how="left", validate="many_to_one", ) assert len(out) == len(sales), "a merge duplicated rows" return out
def monthly_scorecard(lines: pd.DataFrame) -> pd.DataFrame: """One row per store and month with KPIs, shares, ranks and trends.""" card = ( lines.assign( month=lambda d: d["order_date"].dt.to_period("M"), profit=lambda d: d["revenue"] - d["unit_cost"] * d["quantity"], ) .groupby(["region", "store_id", "city", "month"], observed=True) .agg( revenue=("revenue", "sum"), orders=("order_id", "nunique"), profit=("profit", "sum"), size_sqm=("size_sqm", "first"), ) .reset_index() .sort_values(["store_id", "month"]) ) by_store = card.groupby("store_id", observed=True)["revenue"] by_region_month = card.groupby(["region", "month"], observed=True)["revenue"] return card.assign( aov=card["revenue"] / card["orders"], margin=card["profit"] / card["revenue"], per_sqm=card["revenue"] / card["size_sqm"], region_share=card["revenue"] / by_region_month.transform("sum"), region_rank=( by_region_month.rank(ascending=False, method="min").astype("int8") ), rolling_3m=by_store.transform(lambda s: s.rolling(3, min_periods=1).mean()), mom=by_store.pct_change(), )
# --- Load and build ----------------------------------------------------sales = load_sales()stores = pd.read_csv("data/stores.csv")products = pd.read_csv("data/products.csv")print(f"sales: {len(sales)} rows, {sales.memory_usage(deep=True).sum() / 1e6:.2f} MB")
card = sales.pipe(add_dimensions, stores, products).pipe(monthly_scorecard)card_2024 = card[card["month"].dt.year == 2024]print(card.shape, card_2024.shape)
# --- Report ------------------------------------------------------------december = card_2024[card_2024["month"] == pd.Period("2024-12", "M")]report = december.sort_values(["region", "region_rank"])[REPORT_COLUMNS]print(report.round(3).to_string(index=False))trend_cols = ["revenue", "per_sqm", "rolling_3m", "mom"]s12_2024 = card_2024[card_2024["store_id"] == "S12"].set_index("month")[trend_cols]print(s12_2024.tail(4).round(3))
quarterly = card_2024.assign(quarter=card_2024["month"].dt.quarter).pivot_table( index="store_id", columns="quarter", values="revenue", aggfunc="sum", margins=True, margins_name="Total", observed=True,)print(quarterly.div(1000).round(1))
# --- Save --------------------------------------------------------------out_dir = Path("output")out_dir.mkdir(exist_ok=True)out_file = out_dir / "store_scorecard_2024.csv"card_2024.to_csv(out_file, index=False)print(f"saved: {out_file.as_posix()} ({len(pd.read_csv(out_file))} rows)")
# --- Self-checks -------------------------------------------------------shares = card.groupby(["region", "month"], observed=True)["region_share"].sum()assert abs(card["revenue"].sum() - sales["revenue"].sum()) < 0.01assert (shares - 1).abs().max() < 1e-9assert card_2024["store_id"].nunique() == 12assert len(card_2024) == 12 * 12s12 = card[card["store_id"] == "S12"] # sorted by month within the storeassert s12["rolling_3m"].iloc[0] == s12["revenue"].iloc[0]assert abs(s12["rolling_3m"].iloc[2] - s12["revenue"].iloc[:3].mean()) < 1e-9sales: 20228 rows, 1.38 MB(283, 15) (144, 15)region store_id city revenue aov margin region_share region_rank mom East S07 New York 43967.33 244.263 0.466 0.495 1 0.115 East S08 Boston 27803.58 269.938 0.453 0.313 2 0.440 East S09 Philadelphia 17099.27 244.275 0.444 0.192 3 -0.219 North S01 Chicago 40404.83 264.084 0.458 0.514 1 0.525 North S02 Minneapolis 23064.73 240.258 0.468 0.293 2 0.089 North S03 Detroit 15160.59 248.534 0.480 0.193 3 0.269 South S04 Houston 31485.30 264.582 0.468 0.445 1 0.042 South S05 Atlanta 23225.83 219.112 0.493 0.328 2 0.367 South S06 Miami 16074.08 203.469 0.495 0.227 3 -0.252 West S10 Seattle 29547.86 256.938 0.452 0.457 1 0.161 West S11 San Francisco 23765.22 228.512 0.480 0.368 2 0.112 West S12 Denver 11313.15 221.826 0.493 0.175 3 -0.106 revenue per_sqm rolling_3m mommonth2024-09 5348.64 3.962 5515.143 -0.1372024-10 9840.72 7.289 7128.067 0.8402024-11 12647.68 9.369 9279.013 0.2852024-12 11313.15 8.380 11267.183 -0.106quarter 1 2 3 4 Totalstore_idS01 40.7 45.4 52.5 82.4 220.9S02 21.9 27.8 33.1 58.8 141.6S03 16.7 34.9 24.7 38.9 115.2S04 33.8 48.6 47.4 81.0 210.7S05 32.4 31.8 38.5 57.5 160.2S06 23.1 15.0 27.5 45.7 111.4S07 44.9 50.2 62.5 106.2 263.9S08 31.1 32.1 29.5 55.6 148.4S09 23.8 29.0 32.6 47.1 132.5S10 45.6 40.6 49.3 77.7 213.2S11 30.9 29.0 28.4 52.8 141.2S12 26.4 15.0 16.5 33.8 91.8Total 371.5 399.5 442.4 737.5 1950.9saved: output/store_scorecard_2024.csv (144 rows)Run it from the project folder:
python scorecard.pyHow it works:
- Loading.
read_csv(dtype=...)builds the categories while it reads. The table takes 1.38 MB instead of the 3.25 MB of a plainread_csv(lesson Example 8). - Merges. The dimension keys are cast to
categorytoo, so that both sides of each merge have the same dtype.validate="many_to_one"and the length assert would stop the script on a duplicated store, the bug that broke last month’s spreadsheet. - Aggregation.
assignwith lambdas addsmonthandprofitinside the chain. Named aggregation builds the four base columns.observed=Truekeeps the 283 real store-months. Withobserved=False, the categorical keysregionandstore_idwould add rows for combinations that do not exist, such as a North store in the West. - Group columns.
transform("sum")puts the region-month total on each row, so the share is one division.rank(ascending=False, method="min")within region and month gives 1 to the top store;method="min"gives tied stores the same whole rank, soastype("int8")cannot truncate a 1.5. Because the rows are sorted by store and month,rollingandpct_changewithinstore_idlook back over that store’s own previous months. - Reports.
.dt.yearand.dt.quarterwork on the period column. In December, Chicago has the largest increase over November (+52.5%). Every store has its largest quarter in Q4. In S12’s rows, the Decemberrolling_3m(11,267.18) is the mean of S12’s own October to December revenue, which shows that the window stays inside the store. - Checks. The asserts confirm that no revenue was lost or duplicated and that the shares are consistent. They run every month, on every new export.
Alternative: compute the store-month table with pivot_table (stores in rows, months in columns) and use rolling along the columns. The long table of this solution is better here: every KPI is one column, and the CSV loads straight into a dashboard or a database.