Skip to content

31. Polars — Mini-project

The retail chain reviews its 12 stores every January. Until now, an analyst built the review by hand in a spreadsheet from three exports. It took two days, and last year a duplicated store row doubled one store’s revenue.

Write a script, store_pack.py, that builds the 2024 store-performance pack in one run, with Polars. It must use the lazy API, so the same script can later run on a much larger sales history. It must check its joins and cross-check its total with a second engine, so a broken export cannot slip through.

The project uses every part of module 31: scan_csv, expressions in with_columns, filter and group_by().agg(), filter inside agg, window expressions with over, validated joins, a lazy pivot, unpivot, Parquet output and DuckDB.

Three files from the course data folder:

File Rows Used columns
data/sales.csv 20,228 order lines, 2023–2024 order_id, order_date, store_id, region, channel, product_id, quantity, revenue
data/stores.csv 12 stores store_id, city, size_sqm
data/products.csv 30 products product_id, unit_cost

Definitions for the pack:

  • Gross profit of a line = revenue − unit_cost × quantity. Margin = gross profit ÷ revenue.
  • AOV (average order value) = revenue ÷ number of distinct orders.
  • Online share = online revenue ÷ revenue.
  • Revenue per m² = revenue ÷ size_sqm.

Denver (S12) opened in June 2023, so 2024 is its first full year.

Your script must:

  1. Set pl.Config so every printed table is at most 100 characters wide and shows all 12 stores.
  2. Read the three files with pl.scan_csv and keep the whole pipeline lazy until the final tables.
  3. Keep only 2024 lines. Join the unit cost and the store details with validate="m:1".
  4. Build a store KPI table with one row per store: region, rank inside the region by revenue, store id, city, revenue (2 decimals), AOV (2 decimals), margin (3 decimals), online share (3 decimals) and revenue per m² (1 decimal). Sort by region, then rank.
  5. Build a quarter table with one row per store and the columns Q1 to Q4 (revenue rounded to whole dollars), with a lazy pivot.
  6. Find each store’s strongest quarter with unpivot and a window expression.
  7. Write both tables to output/ as Parquet, read the KPI file back and check it against the table in memory with assert_frame_equal.
  8. Recompute the 2024 total revenue with DuckDB directly from the CSV file and check it against the sum of the KPI table.
  9. Print the report below, exactly. Use f-strings for every number.
  10. Make every printed result order-deterministic, and end with assert checks.

The expected report:

Expected output
Store performance pack 2024
---------------------------
Stores: 12, revenue: 1,950,934.24 USD (DuckDB check: ok)
Gross margin: 49.5%
Leaders: East S07 New York | North S01 Chicago | South S04 Houston | West S10 Seattle
Best revenue per m2: S10 Seattle, 86.0 USD
Highest online share: S02 Minneapolis, 52.3%
Strongest quarter: Q4 for 12 of 12 stores
Files: store_kpis_2024.parquet, store_quarters_2024.parquet
  1. Set up. Create store_pack.py. Import Path, duckdb and polars. Set the display options, a YEAR = 2024 constant and an output/ folder.

  2. Scan. Create three LazyFrames with pl.scan_csv(..., try_parse_dates=True). Print collect_schema() of the sales scan to see the dtypes without reading the file.

  3. Enrich the lines. Filter the year, join unit_cost and the store columns with validate="m:1", and add gross_profit and a quarter label with pl.format("Q{}", ...). Check the column names with collect_schema().names().

  4. Store KPIs. Group by the store columns. Aggregate revenue, gross profit, distinct orders and online revenue (pl.col("revenue").filter(online).sum()). Add the ratios and the rank with rank("ordinal", descending=True).over("region"). Round last. Sort, then collect().

  5. Quarter table. Group by store and quarter, then pivot(on="quarter", on_columns=["Q1", "Q2", "Q3", "Q4"], ...). A lazy pivot needs on_columns. Sort by store and collect.

  6. Strongest quarter. unpivot the quarter table and keep the rows where the revenue equals pl.col("revenue").max().over("store_id").

  7. Save and reread. Write both tables with write_parquet. Read the KPI file back and compare with polars.testing.assert_frame_equal. Unlike equals, it also checks the dtypes, and a file round trip is exactly where a dtype can change.

  8. Cross-check. Query the CSV file with DuckDB: SELECT round(sum(revenue), 2) FROM 'data/sales.csv' WHERE year(order_date) = 2024. Compare with the KPI total using math.isclose and a tolerance of 1 cent.

  9. Report. Pick the leaders (rank 1), the best revenue per m² and the highest online share from the KPI table. Print the report with f-strings.

Criterion Excellent (3) Adequate (2) Needs work (1)
Correctness All numbers match the expected report; DuckDB check passes One KPI off by rounding Totals wrong, or a join duplicates rows
Lazy pipeline One lazy chain per table, collect() only at the end Lazy, but collects between steps Eager read_csv with Python loops
Expressions filter inside agg, over for ranks and maxima, no map_elements Correct, with an extra join or helper column Row-by-row Python code
Safety validate="m:1" on both joins; Parquet reread and compared; asserts at the end Some checks No checks
Determinism Every printed table sorted or ordered explicitly One unsorted print that happens to look right Output order changes between runs
Readability Named expressions (online = ...), clear names, comments on the definitions Mostly clear Long unexplained chains
  • Turn the pipeline into a function store_pack(sales_lf, stores_lf, products_lf, year) that returns the two LazyFrames. Test it with polars.testing.assert_frame_equal on a tiny hand-made table (module 14).
  • Add a command-line interface with argparse (module 08): python store_pack.py --year 2023 --out output/2023.
  • Add a 2023 column and the growth in percent to the KPI table. Denver has no full 2023; show its growth as null and explain why.
  • Run the same pipeline with collect(engine="streaming") and compare it with the in-memory result. The streaming engine adds floats in a different order, so compare with assert_frame_equal (it allows a small float tolerance by default) or compare the rounded tables.
  • Write the KPI table to CSV for the finance team with write_csv, and check that pl.read_csv reads back the same dtypes.
Reference solution

The solution is one script, shown here in parts. Each part runs after the previous one.

Part 1: set up and scan.

import math
from pathlib import Path
import duckdb
import polars as pl
from polars.testing import assert_frame_equal
pl.Config.set_tbl_rows(12)
pl.Config.set_tbl_cols(10)
pl.Config.set_tbl_width_chars(100)
pl.Config.set_fmt_str_lengths(30)
pl.Config.set_fmt_float("full")
YEAR = 2024
OUT = Path("output")
OUT.mkdir(exist_ok=True)
sales_lf = pl.scan_csv("data/sales.csv", try_parse_dates=True)
stores_lf = pl.scan_csv("data/stores.csv", try_parse_dates=True)
products_lf = pl.scan_csv("data/products.csv", try_parse_dates=True)
print(sales_lf.collect_schema()["order_date"], sales_lf.collect_schema().len())
Output
Date 13

Part 2: enrich the 2024 lines.

lines = (
sales_lf.filter(pl.col("order_date").dt.year() == YEAR)
.join(
products_lf.select("product_id", "unit_cost"),
on="product_id",
how="left",
validate="m:1",
)
.join(
stores_lf.select("store_id", "city", "size_sqm"),
on="store_id",
how="left",
validate="m:1",
)
.with_columns(
# gross profit = revenue minus the cost of the goods sold
gross_profit=pl.col("revenue") - pl.col("unit_cost") * pl.col("quantity"),
quarter=pl.format("Q{}", pl.col("order_date").dt.quarter()),
)
)
print(lines.collect_schema().names()[-5:])
Output
['unit_cost', 'city', 'size_sqm', 'gross_profit', 'quarter']

Part 3: the store KPI table.

online = pl.col("channel") == "online"
store_kpis = (
lines.group_by("store_id", "city", "region", "size_sqm")
.agg(
revenue=pl.col("revenue").sum(),
gross_profit=pl.col("gross_profit").sum(),
orders=pl.col("order_id").n_unique(),
online_revenue=pl.col("revenue").filter(online).sum(),
)
.with_columns(
# every expression here reads the unrounded inputs
rank=pl.col("revenue").rank("ordinal", descending=True).over("region"),
aov=(pl.col("revenue") / pl.col("orders")).round(2),
margin=(pl.col("gross_profit") / pl.col("revenue")).round(3),
online_share=(pl.col("online_revenue") / pl.col("revenue")).round(3),
per_sqm=(pl.col("revenue") / pl.col("size_sqm")).round(1),
revenue=pl.col("revenue").round(2),
)
.sort("region", "rank")
.collect()
)
kpi_columns = ["region", "rank", "store_id", "city", "revenue", "aov", "margin"]
print(store_kpis.select(*kpi_columns, "online_share", "per_sqm"))
Output
shape: (12, 9)
┌────────┬──────┬──────────┬───────────────┬───────────┬────────┬────────┬──────────────┬─────────┐
│ region ┆ rank ┆ store_id ┆ city ┆ revenue ┆ aov ┆ margin ┆ online_share ┆ per_sqm │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ str ┆ str ┆ f64 ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞════════╪══════╪══════════╪═══════════════╪═══════════╪════════╪════════╪══════════════╪═════════╡
│ East ┆ 1 ┆ S07 ┆ New York ┆ 263924 ┆ 249.46 ┆ 0.485 ┆ 0.433 ┆ 77.6 │
│ East ┆ 2 ┆ S08 ┆ Boston ┆ 148352.73 ┆ 239.28 ┆ 0.486 ┆ 0.479 ┆ 72.4 │
│ East ┆ 3 ┆ S09 ┆ Philadelphia ┆ 132488.36 ┆ 250.92 ┆ 0.487 ┆ 0.485 ┆ 75.3 │
│ North ┆ 1 ┆ S01 ┆ Chicago ┆ 220899.08 ┆ 246.26 ┆ 0.495 ┆ 0.434 ┆ 77.5 │
│ North ┆ 2 ┆ S02 ┆ Minneapolis ┆ 141643.5 ┆ 231.07 ┆ 0.498 ┆ 0.523 ┆ 72.6 │
│ North ┆ 3 ┆ S03 ┆ Detroit ┆ 115186.83 ┆ 240.47 ┆ 0.509 ┆ 0.434 ┆ 81.1 │
│ South ┆ 1 ┆ S04 ┆ Houston ┆ 210733.14 ┆ 237.31 ┆ 0.502 ┆ 0.493 ┆ 68 │
│ South ┆ 2 ┆ S05 ┆ Atlanta ┆ 160171.41 ┆ 231.13 ┆ 0.502 ┆ 0.473 ┆ 69.6 │
│ South ┆ 3 ┆ S06 ┆ Miami ┆ 111360.45 ┆ 231.52 ┆ 0.503 ┆ 0.467 ┆ 66.3 │
│ West ┆ 1 ┆ S10 ┆ Seattle ┆ 213238.5 ┆ 255.68 ┆ 0.48 ┆ 0.439 ┆ 86 │
│ West ┆ 2 ┆ S11 ┆ San Francisco ┆ 141176.27 ┆ 220.24 ┆ 0.503 ┆ 0.43 ┆ 74.7 │
│ West ┆ 3 ┆ S12 ┆ Denver ┆ 91759.97 ┆ 216.42 ┆ 0.514 ┆ 0.447 ┆ 68 │
└────────┴──────┴──────────┴───────────────┴───────────┴────────┴────────┴──────────────┴─────────┘

All the ratios sit in one with_columns, so each of them reads the revenue before it is rounded. The rank restarts in each region because of over("region").

Part 4: the quarter table and the strongest quarter.

quarters = ["Q1", "Q2", "Q3", "Q4"]
quarterly = (
lines.group_by("store_id", "quarter")
.agg(pl.col("revenue").sum().round(0))
.pivot(on="quarter", on_columns=quarters, index="store_id", values="revenue")
.sort("store_id")
.collect()
)
print(quarterly.head(4))
best = quarterly.unpivot(
index="store_id", variable_name="quarter", value_name="revenue"
).filter(pl.col("revenue") == pl.col("revenue").max().over("store_id"))
best_counts = best.group_by("quarter").agg(stores=pl.len()).sort("quarter")
print(best_counts)
Output
shape: (4, 5)
┌──────────┬───────┬───────┬───────┬───────┐
│ store_id ┆ Q1 ┆ Q2 ┆ Q3 ┆ Q4 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞══════════╪═══════╪═══════╪═══════╪═══════╡
│ S01 ┆ 40722 ┆ 45357 ┆ 52453 ┆ 82368 │
│ S02 ┆ 21926 ┆ 27811 ┆ 33103 ┆ 58803 │
│ S03 ┆ 16664 ┆ 34934 ┆ 24725 ┆ 38865 │
│ S04 ┆ 33792 ┆ 48602 ┆ 47361 ┆ 80978 │
└──────────┴───────┴───────┴───────┴───────┘
shape: (1, 2)
┌─────────┬────────┐
│ quarter ┆ stores │
│ --- ┆ --- │
│ str ┆ u32 │
╞═════════╪════════╡
│ Q4 ┆ 12 │
└─────────┴────────┘

The lazy pivot needs on_columns, because the optimizer must know the new column names before it reads data. The list also fixes the column order.

Part 5: save, reread and cross-check.

kpi_file = OUT / f"store_kpis_{YEAR}.parquet"
quarter_file = OUT / f"store_quarters_{YEAR}.parquet"
store_kpis.write_parquet(kpi_file)
quarterly.write_parquet(quarter_file)
reread = pl.read_parquet(kpi_file)
assert_frame_equal(reread, store_kpis) # names, dtypes and values
duck_total = duckdb.sql(
"SELECT round(sum(revenue), 2) AS total FROM 'data/sales.csv' "
f"WHERE year(order_date) = {YEAR}"
).pl().item()
total = store_kpis["revenue"].sum()
duck_ok = math.isclose(total, duck_total, abs_tol=0.01)
print(reread.schema == store_kpis.schema, duck_total, duck_ok)
Output
True 1950934.24 True

assert_frame_equal raises an AssertionError if the Parquet file changed a name, a dtype or a value; equals would miss a dtype change. DuckDB reads the CSV file on its own, with its own parser and its own sum. Two engines that agree to the cent make a broken join or filter very unlikely. The f-string puts a constant year into the SQL; never build SQL from user input this way (module 30 shows parameters).

Part 6: the report.

gross_margin = store_kpis["gross_profit"].sum() / total
leaders = store_kpis.filter(pl.col("rank") == 1)
# store_id breaks ties: per_sqm is rounded, and S04 and S12 share 68.0
best_sqm = store_kpis.sort(["per_sqm", "store_id"], descending=[True, False]).row(
0, named=True
)
best_online = store_kpis.sort(
["online_share", "store_id"], descending=[True, False]
).row(0, named=True)
q4_count = best.filter(pl.col("quarter") == "Q4").height
leader_text = " | ".join(
f"{r['region']} {r['store_id']} {r['city']}" for r in leaders.iter_rows(named=True)
)
print(f"Store performance pack {YEAR}")
print("-" * 27)
check = "ok" if duck_ok else "FAILED"
print(f"Stores: {store_kpis.height}, revenue: {total:,.2f} USD (DuckDB check: {check})")
print(f"Gross margin: {gross_margin:.1%}")
print(f"Leaders: {leader_text}")
print(
f"Best revenue per m2: {best_sqm['store_id']} {best_sqm['city']}, "
f"{best_sqm['per_sqm']:.1f} USD"
)
print(
f"Highest online share: {best_online['store_id']} {best_online['city']}, "
f"{best_online['online_share']:.1%}"
)
print(f"Strongest quarter: Q4 for {q4_count} of {quarterly.height} stores")
print(f"Files: {kpi_file.name}, {quarter_file.name}")
assert store_kpis.height == 12 and quarterly.height == 12
assert duck_ok
assert leaders["region"].to_list() == ["East", "North", "South", "West"]
assert store_kpis.group_by("region").agg(pl.len())["len"].to_list() == [3, 3, 3, 3]
Output
Store performance pack 2024
---------------------------
Stores: 12, revenue: 1,950,934.24 USD (DuckDB check: ok)
Gross margin: 49.5%
Leaders: East S07 New York | North S01 Chicago | South S04 Houston | West S10 Seattle
Best revenue per m2: S10 Seattle, 86.0 USD
Highest online share: S02 Minneapolis, 52.3%
Strongest quarter: Q4 for 12 of 12 stores
Files: store_kpis_2024.parquet, store_quarters_2024.parquet

Why it is built this way:

  1. Lazy until the end. Each table is one chain that starts from a scan and ends with collect(). The optimizer reads only the columns that each table needs and pushes the year filter into the CSV reader.
  2. lines is reused. Both tables start from the same LazyFrame. Each collect() runs its own optimized plan, so nothing is computed that a table does not use.
  3. Validated joins. A duplicated store or product row would stop the script with a ComputeError instead of inflating the totals, last year’s problem.
  4. Determinism. The KPI table is sorted by region and rank, the quarter table by store id, the quarter counts by quarter. row(0) after a sort picks a well-defined row.
  5. Two engines. The DuckDB total is an independent check of the Polars pipeline, not a copy of it.