Skip to content

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.

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.

Your script must:

  1. Read data/sales.csv with compact dtypes set at load time: category for the six low-cardinality text columns and int8 for quantity. Print the number of rows and the memory in MB.
  2. Attach city, size_sqm and unit_cost with two left merges. Validate both as many-to-one and assert that the row count does not change.
  3. Build one row per store and month (region, store_id, city, month) with named aggregation: revenue, orders (distinct orders), profit and size_sqm.
  4. Add these columns without loops over rows:
    • aov (revenue per order), margin (profit / revenue) and per_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.
  5. Write the steps as functions with type hints and join them with pipe.
  6. Print the December 2024 scorecard, sorted by region and rank, with the columns region, store_id, city, revenue, aov, margin, region_share, region_rank and mom, rounded to 3 decimals.
  7. Print S12’s last four months of 2024 with month as the index and the columns revenue, per_sqm, rolling_3m and mom, rounded to 3 decimals. This shows that the trends stay within one store.
  8. Print a 2024 revenue table in thousands of USD: one row per store, one column per quarter, with totals.
  9. Save the 2024 scorecard to output/store_scorecard_2024.csv.
  10. End with assert checks: 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 first rolling_3m equals its first revenue, and its third rolling_3m is the mean of its first three months.

The expected report:

Expected output
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 mom
month
2024-09 5348.64 3.962 5515.143 -0.137
2024-10 9840.72 7.289 7128.067 0.840
2024-11 12647.68 9.369 9279.013 0.285
2024-12 11313.15 8.380 11267.183 -0.106
quarter 1 2 3 4 Total
store_id
S01 40.7 45.4 52.5 82.4 220.9
S02 21.9 27.8 33.1 58.8 141.6
S03 16.7 34.9 24.7 38.9 115.2
S04 33.8 48.6 47.4 81.0 210.7
S05 32.4 31.8 38.5 57.5 160.2
S06 23.1 15.0 27.5 45.7 111.4
S07 44.9 50.2 62.5 106.2 263.9
S08 31.1 32.1 29.5 55.6 148.4
S09 23.8 29.0 32.6 47.1 132.5
S10 45.6 40.6 49.3 77.7 213.2
S11 30.9 29.0 28.4 52.8 141.2
S12 26.4 15.0 16.5 33.8 91.8
Total 371.5 399.5 442.4 737.5 1950.9
saved: 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.

  1. 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 with memory_usage(deep=True).sum().

  2. Merge the dimensions. Write add_dimensions(sales, stores, products). Select only the columns you need from each dimension table, merge with how="left" and validate="many_to_one", and assert the length. Cast the dimension keys to category first, so that both sides of each merge have the same dtype.

  3. Aggregate per store and month. In monthly_scorecard(lines), add month with .dt.to_period("M") and profit with assign, then group by region, store, city and month. observed=True is 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.

  4. Add the ratios. aov, margin and per_sqm are column divisions after the aggregation.

  5. 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 by store_id for rolling_3m and mom (pct_change()).

  6. Report. Filter 2024 with .dt.year on the period column. Select December with pd.Period("2024-12", "M"). Use to_string(index=False) for the scorecard. Build the quarterly table with pivot_table(..., margins=True, margins_name="Total") and .div(1000).round(1).

  7. Save and check. Create output/ with Path.mkdir(exist_ok=True), write the CSV with index=False and add the asserts.

  8. Run it with python scorecard.py and compare every line with the expected report.

A skeleton to start from:

scorecard.py (starter)
# 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, assert
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
  1. Add a yoy column: the change from the same month one year earlier. Use groupby("store_id")["revenue"].shift(12) and explain why S12 has NaN until mid-2024.
  2. Flag “watch” stores: a negative mom for two months in a row. Use shift(1) within each store.
  3. Add an online_share column per store and month. Compute it before the aggregation with where, as in lesson Example 1.
  4. Write the scorecard to Parquet as well, and compare the file sizes and the dtypes after reading both files back.
  5. Turn the script into a command-line tool with argparse (module 08) that takes the month to report, such as --month 2024-11.

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
# 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.01
assert (shares - 1).abs().max() < 1e-9
assert card_2024["store_id"].nunique() == 12
assert len(card_2024) == 12 * 12
s12 = card[card["store_id"] == "S12"] # sorted by month within the store
assert s12["rolling_3m"].iloc[0] == s12["revenue"].iloc[0]
assert abs(s12["rolling_3m"].iloc[2] - s12["revenue"].iloc[:3].mean()) < 1e-9
Output
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 mom
month
2024-09 5348.64 3.962 5515.143 -0.137
2024-10 9840.72 7.289 7128.067 0.840
2024-11 12647.68 9.369 9279.013 0.285
2024-12 11313.15 8.380 11267.183 -0.106
quarter 1 2 3 4 Total
store_id
S01 40.7 45.4 52.5 82.4 220.9
S02 21.9 27.8 33.1 58.8 141.6
S03 16.7 34.9 24.7 38.9 115.2
S04 33.8 48.6 47.4 81.0 210.7
S05 32.4 31.8 38.5 57.5 160.2
S06 23.1 15.0 27.5 45.7 111.4
S07 44.9 50.2 62.5 106.2 263.9
S08 31.1 32.1 29.5 55.6 148.4
S09 23.8 29.0 32.6 47.1 132.5
S10 45.6 40.6 49.3 77.7 213.2
S11 30.9 29.0 28.4 52.8 141.2
S12 26.4 15.0 16.5 33.8 91.8
Total 371.5 399.5 442.4 737.5 1950.9
saved: output/store_scorecard_2024.csv (144 rows)

Run it from the project folder:

Terminal
python scorecard.py

How it works:

  1. Loading. read_csv(dtype=...) builds the categories while it reads. The table takes 1.38 MB instead of the 3.25 MB of a plain read_csv (lesson Example 8).
  2. Merges. The dimension keys are cast to category too, 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.
  3. Aggregation. assign with lambdas adds month and profit inside the chain. Named aggregation builds the four base columns. observed=True keeps the 283 real store-months. With observed=False, the categorical keys region and store_id would add rows for combinations that do not exist, such as a North store in the West.
  4. 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, so astype("int8") cannot truncate a 1.5. Because the rows are sorted by store and month, rolling and pct_change within store_id look back over that store’s own previous months.
  5. Reports. .dt.year and .dt.quarter work 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 December rolling_3m (11,267.18) is the mean of S12’s own October to December revenue, which shows that the window stays inside the store.
  6. 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.