Skip to content

31. Polars — Exercises

These exercises practice every idea of the Polars lesson. They use the course tables data/sales.csv, data/stores.csv, data/products.csv and data/sales_sample.parquet.

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block and then the starter code into a script (for example exercise.py). Replace each to-do comment with your code.
  3. Run the script with python exercise.py. Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Each solution ends with assert checks. Add the same checks to your own code: they turn “it looks right” into “it is right”.

Every exercise starts from this block. It fixes the display options of the lesson and loads the three tables.

import polars as pl
pl.Config.set_tbl_rows(10)
pl.Config.set_tbl_cols(8)
pl.Config.set_tbl_width_chars(100)
pl.Config.set_fmt_str_lengths(30)
pl.Config.set_fmt_float("full")
sales = pl.read_csv("data/sales.csv", try_parse_dates=True)
stores = pl.read_csv("data/stores.csv", try_parse_dates=True)
products = pl.read_csv("data/products.csv", try_parse_dates=True)
Warm-up

The regional manager sends yearly revenue targets for three stores: S01 400,000, S04 380,000 and S07 450,000. Build a DataFrame targets with the columns store_id and target. Print it, then print its height and the dtype of target.

Expected output
shape: (3, 2)
┌──────────┬────────┐
│ store_id ┆ target │
│ --- ┆ --- │
│ str ┆ i64 │
╞══════════╪════════╡
│ S01 ┆ 400000 │
│ S04 ┆ 380000 │
│ S07 ┆ 450000 │
└──────────┴────────┘
3 Int64
Starter
# TODO: build targets from a dict of two lists
# TODO: print the table, then its height and the dtype of "target"
Hint 1

pl.DataFrame({"col_a": [...], "col_b": [...]}) builds a table from a dict of equal-length lists.

Hint 2

df.height is the row count. df.schema["target"] (or df["target"].dtype) gives the dtype.

Solution
targets = pl.DataFrame(
{"store_id": ["S01", "S04", "S07"], "target": [400_000, 380_000, 450_000]}
)
print(targets)
print(targets.height, targets.schema["target"])
assert targets.shape == (3, 2)
assert targets.schema["target"] == pl.Int64
Output
shape: (3, 2)
┌──────────┬────────┐
│ store_id ┆ target │
│ --- ┆ --- │
│ str ┆ i64 │
╞══════════╪════════╡
│ S01 ┆ 400000 │
│ S04 ┆ 380000 │
│ S07 ┆ 450000 │
└──────────┴────────┘
3 Int64

How it works:

  1. Each dict key becomes a column name and each list becomes a column.
  2. Polars infers String for the ids and Int64 for the whole numbers. The underscores in 400_000 only help you read the literal.
  3. height counts rows; schema maps each column name to its dtype.

Alternative: build the table from rows with orient="row" and an explicit schema. This fits data that arrives as a list of records.

rows = [("S01", 400_000), ("S04", 380_000), ("S07", 450_000)]
targets = pl.DataFrame(
rows, schema={"store_id": pl.String, "target": pl.Int64}, orient="row"
)
print(targets.shape, targets.columns)
Output
(3, 2) ['store_id', 'target']
Warm-up

Fix the bug: the starter reads data/stores.csv and wants the year in which each store opened, but .dt.year() fails. Fix the read so the code works, and print the dtype of opened and the three most recently opened stores, newest first.

Expected output
Date
shape: (3, 3)
┌──────────┬──────────────┬──────┐
│ store_id ┆ city ┆ year │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i32 │
╞══════════╪══════════════╪══════╡
│ S12 ┆ Denver ┆ 2023 │
│ S06 ┆ Miami ┆ 2018 │
│ S09 ┆ Philadelphia ┆ 2017 │
└──────────┴──────────────┴──────┘
Starter
raw = pl.read_csv("data/stores.csv")
newest = (
raw.with_columns(year=pl.col("opened").dt.year())
.sort("opened", descending=True)
.select("store_id", "city", "year")
.head(3)
)
# TODO: fix the read so that "opened" is a date, then print its dtype and newest
Hint 1

Print raw.schema["opened"]. Which dtype does a column need before .dt works?

Hint 2

pl.read_csv(..., try_parse_dates=True) parses ISO date text into Date.

Solution
raw = pl.read_csv("data/stores.csv", try_parse_dates=True)
newest = (
raw.with_columns(year=pl.col("opened").dt.year())
.sort("opened", descending=True)
.select("store_id", "city", "year")
.head(3)
)
print(raw.schema["opened"])
print(newest)
assert raw.schema["opened"] == pl.Date
assert newest["store_id"].to_list() == ["S12", "S06", "S09"]
Output
Date
shape: (3, 3)
┌──────────┬──────────────┬──────┐
│ store_id ┆ city ┆ year │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i32 │
╞══════════╪══════════════╪══════╡
│ S12 ┆ Denver ┆ 2023 │
│ S06 ┆ Miami ┆ 2018 │
│ S09 ┆ Philadelphia ┆ 2017 │
└──────────┴──────────────┴──────┘

How it works:

  1. Without try_parse_dates=True, opened is String, and .dt.year() on text raises an InvalidOperationError.
  2. With the option, Polars recognizes the YYYY-MM-DD pattern and stores real dates.
  3. Sorting a Date column sorts by time. Sorting the text would also work for ISO dates, but .dt would still fail.

Alternative: keep the read as it is and parse the one column with the .str namespace. This is the way to go when the format is not ISO (pass the format, for example "%d/%m/%Y").

raw = pl.read_csv("data/stores.csv")
fixed = raw.with_columns(pl.col("opened").str.to_date("%Y-%m-%d"))
print(fixed.schema["opened"], fixed["opened"].max())
Output
Date 2023-06-15
Warm-up

A dashboard shows revenue in thousands of USD. From sales, select order_id, product and a new column revenue_k (revenue divided by 1,000, rounded to 3 decimals). Print the first 3 rows.

Expected output
shape: (3, 3)
┌──────────┬────────────────────────┬───────────┐
│ order_id ┆ product ┆ revenue_k │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 │
╞══════════╪════════════════════════╪═══════════╡
│ O000001 ┆ Cotton Bed Sheet Set ┆ 0.066 │
│ O000002 ┆ Running Socks 3-Pack ┆ 0.015 │
│ O000003 ┆ Organic Cotton T-Shirt ┆ 0.02 │
└──────────┴────────────────────────┴───────────┘
Starter
# TODO: select order_id, product and revenue_k from sales
# TODO: print the first 3 rows
Hint 1

select takes column names as strings and new columns as expressions.

Hint 2

Name a new column with a keyword argument: revenue_k=(pl.col("revenue") / 1000).round(3).

Solution
dashboard = sales.select(
"order_id",
"product",
revenue_k=(pl.col("revenue") / 1000).round(3),
).head(3)
print(dashboard)
assert dashboard.columns == ["order_id", "product", "revenue_k"]
assert dashboard["revenue_k"][0] == 0.066
Output
shape: (3, 3)
┌──────────┬────────────────────────┬───────────┐
│ order_id ┆ product ┆ revenue_k │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 │
╞══════════╪════════════════════════╪═══════════╡
│ O000001 ┆ Cotton Bed Sheet Set ┆ 0.066 │
│ O000002 ┆ Running Socks 3-Pack ┆ 0.015 │
│ O000003 ┆ Organic Cotton T-Shirt ┆ 0.02 │
└──────────┴────────────────────────┴───────────┘

How it works:

  1. "order_id" and "product" are short for pl.col("order_id") and pl.col("product").
  2. The keyword argument names the new column. The parentheses make the division run before round.
  3. select returns only the three columns; head(3) keeps the first three rows.

Alternative: use .alias() instead of a keyword argument. Both forms give the same table; keyword arguments read better when you add many columns.

dashboard = sales.select(
"order_id", "product", (pl.col("revenue") / 1000).round(3).alias("revenue_k")
).head(3)
print(dashboard.columns)
Output
['order_id', 'product', 'revenue_k']
Warm-up

Marketing asks how many online sales lines had the deepest discount (20%) and how much revenue they brought in. Print the line count and the revenue rounded to 2 decimals on one line.

Expected output
646 94994.03
Starter
# TODO: keep the online lines with discount 0.2
# TODO: print the number of lines and their total revenue
Hint 1

filter accepts several predicates separated by commas. All must be true.

Hint 2

df.height counts rows. df["revenue"].sum() adds a column; wrap it in round(..., 2).

Solution
deep = sales.filter(pl.col("channel") == "online", pl.col("discount") == 0.2)
total = round(deep["revenue"].sum(), 2)
print(deep.height, total)
assert deep["discount"].unique().to_list() == [0.2]
assert deep.height < sales.height
Output
646 94994.03

How it works:

  1. The two predicates are combined with “and”.
  2. Comparing a float with == 0.2 is safe here: the file stores the exact literal 0.2, so Polars reads the same float.
  3. deep["revenue"] is a Series, and sum() returns a Python float.

Alternative: answer both questions in one select with expressions. pl.len() counts rows.

summary = sales.filter(
(pl.col("channel") == "online") & (pl.col("discount") == 0.2)
).select(lines=pl.len(), revenue=pl.col("revenue").sum().round(2))
print(summary.row(0))
Output
(646, 94994.03)

M31-W05 · Predict select versus with_columns

Section titled “M31-W05 · Predict select versus with_columns”
Warm-up

Predict the output: read the code and write down the three printed lines before you run it.

Starter
df = pl.DataFrame({"store_id": ["S01", "S02"], "units": [3, 5]})
a = df.select(pl.col("units") * 2)
b = df.with_columns(pl.col("units") * 2)
c = df.with_columns(double=pl.col("units") * 2)
print(a.columns, b.columns, c.columns)
print(df["units"].to_list(), b["units"].to_list(), c["units"].to_list())
print(df.filter(pl.col("units") > 3).height)
# TODO: write your prediction for each printed line here

Acceptance criteria: Write your prediction line by line, then run the code. Your prediction matches the Output in the solution.

Hint 1

An expression keeps the name of the column it starts from unless you rename it.

Hint 2

with_columns replaces a column that has the same name. Contexts never change df itself.

Solution
df = pl.DataFrame({"store_id": ["S01", "S02"], "units": [3, 5]})
a = df.select(pl.col("units") * 2)
b = df.with_columns(pl.col("units") * 2)
c = df.with_columns(double=pl.col("units") * 2)
print(a.columns, b.columns, c.columns)
print(df["units"].to_list(), b["units"].to_list(), c["units"].to_list())
print(df.filter(pl.col("units") > 3).height)
assert a.columns == ["units"]
assert df["units"].to_list() == [3, 5]
Output
['units'] ['store_id', 'units'] ['store_id', 'units', 'double']
[3, 5] [6, 10] [3, 5]
1

How it works:

  1. select returns only the expression’s result. pl.col("units") * 2 is still named units.
  2. b replaces units with the doubled values, because the new column has the same name.
  3. c adds a new column double and keeps units as it was.
  4. No context changes df. Every call returns a new DataFrame, so df["units"] is still [3, 5].
  5. Only S02 has more than 3 units.

M31-W06 · Price bands with when, then and otherwise

Section titled “M31-W06 · Price bands with when, then and otherwise”
Warm-up

The catalog team groups products into price bands: budget below 30 USD, mid from 30 up to (not including) 150 USD, and premium from 150 USD. Add a column band to products and print the number of products per band, sorted by band name.

Expected output
shape: (3, 2)
┌─────────┬──────────┐
│ band ┆ products │
│ --- ┆ --- │
│ str ┆ u32 │
╞═════════╪══════════╡
│ budget ┆ 9 │
│ mid ┆ 12 │
│ premium ┆ 9 │
└─────────┴──────────┘
Starter
# TODO: add band with pl.when(...).then(...).when(...).then(...).otherwise(...)
# TODO: count products per band and sort by band
Hint 1

The first true condition wins. Test < 30 first, then < 150.

Hint 2

Wrap constant text in pl.lit("budget"). Count with group_by("band").agg(pl.len()).

Solution
banded = products.with_columns(
band=pl.when(pl.col("unit_price") < 30)
.then(pl.lit("budget"))
.when(pl.col("unit_price") < 150)
.then(pl.lit("mid"))
.otherwise(pl.lit("premium"))
)
counts = banded.group_by("band").agg(pl.len().alias("products")).sort("band")
print(counts)
assert counts["products"].sum() == 30
assert counts["band"].to_list() == ["budget", "mid", "premium"]
Output
shape: (3, 2)
┌─────────┬──────────┐
│ band ┆ products │
│ --- ┆ --- │
│ str ┆ u32 │
╞═════════╪══════════╡
│ budget ┆ 9 │
│ mid ┆ 12 │
│ premium ┆ 9 │
└─────────┴──────────┘

How it works:

  1. The chain checks the conditions in order, like if/elif/else. A price of 29.99 is caught by the first branch.
  2. A price of 150 or more fails both tests and gets premium from otherwise.
  3. group_by plus sort("band") gives a fixed order.

Alternative: bin_intervals puts numbers into bins between breakpoints and labels them. Its bins include the lower edge ([30, 150)) by default, as the task requires, and it returns an Enum column. It replaces cut, which Polars 2 deprecates, but it is not a drop-in swap: cut bins include the upper edge, and labels= is required. The Polars documentation still marks bin_intervals as experimental.

banded = products.with_columns(
band=pl.col("unit_price").bin_intervals(
[30, 150], labels=["budget", "mid", "premium"]
)
)
print(banded["band"].value_counts().sort("band"))
Output
shape: (3, 2)
┌─────────┬───────┐
│ band ┆ count │
│ --- ┆ --- │
│ enum ┆ u32 │
╞═════════╪═══════╡
│ budget ┆ 9 │
│ mid ┆ 12 │
│ premium ┆ 9 │
└─────────┴───────┘

M31-W07 · Clean product codes with the str namespace

Section titled “M31-W07 · Clean product codes with the str namespace”
Warm-up

A warehouse system needs short category codes: the first three letters of the category in capital letters (ELE, HOM, …). It also wants the names of all products that contain the word Set. Print the sorted list of distinct codes, then the sorted list of matching product names.

Expected output
['BEA', 'BOO', 'CLO', 'ELE', 'HOM', 'SPO']
["Chef's Knife Set", 'Cotton Bed Sheet Set', 'Shampoo and Conditioner Set']
Starter
# TODO: build the code with .str.slice and .str.to_uppercase
# TODO: print the sorted distinct codes
# TODO: filter products whose name contains "Set" and print their sorted names
Hint 1

.str.slice(0, 3) takes the first three characters. Chain .str.to_uppercase() after it.

Hint 2

unique() does not keep any order; sort its result. .str.contains("Set") gives a Boolean column for filter.

Solution
codes = products.select(
code=pl.col("category").str.slice(0, 3).str.to_uppercase()
)["code"]
print(sorted(codes.unique().to_list()))
sets = products.filter(pl.col("product").str.contains("Set"))
print(sorted(sets["product"].to_list()))
assert codes.n_unique() == 6
assert len(sets) == 3
Output
['BEA', 'BOO', 'CLO', 'ELE', 'HOM', 'SPO']
["Chef's Knife Set", 'Cotton Bed Sheet Set', 'Shampoo and Conditioner Set']

How it works:

  1. .str.slice(0, 3) and .str.to_uppercase() run on every row of the column at once.
  2. unique() returns the six distinct codes in no fixed order; sorted() fixes it.
  3. .str.contains takes a regular expression. Set has no special characters, so it matches the literal word.

Alternative: pass literal=True when the pattern may contain regex characters such as . or +, and let Polars sort with unique().sort().

codes = products["category"].str.slice(0, 3).str.to_uppercase().unique().sort()
print(codes.to_list())
print(products.filter(pl.col("product").str.contains("Set", literal=True)).height)
Output
['BEA', 'BOO', 'CLO', 'ELE', 'HOM', 'SPO']
3
Warm-up

Fix the bug: the starter should label each line web or shop and count the lines per label. It has two bugs. One raises an error. The other gives a different row order from run to run. Fix both and print the counts sorted by label.

Expected output
shape: (2, 2)
┌───────┬───────┐
│ label ┆ lines │
│ --- ┆ --- │
│ str ┆ u32 │
╞═══════╪═══════╡
│ shop ┆ 11733 │
│ web ┆ 8495 │
└───────┴───────┘
Starter
labeled = sales.with_columns(
label=pl.when(pl.col("channel") == "online").then("web").otherwise("shop")
)
print(labeled.group_by("label").agg(pl.len().alias("lines")))
# TODO: fix the two bugs
Hint 1

Run the starter and read the error. Which column does Polars look for?

Hint 2

Inside then and otherwise, a string is a column name. Constants need pl.lit(). Group order needs sort.

Solution
labeled = sales.with_columns(
label=pl.when(pl.col("channel") == "online")
.then(pl.lit("web"))
.otherwise(pl.lit("shop"))
)
counts = labeled.group_by("label").agg(pl.len().alias("lines")).sort("label")
print(counts)
assert counts["lines"].sum() == sales.height
assert counts["label"].to_list() == ["shop", "web"]
Output
shape: (2, 2)
┌───────┬───────┐
│ label ┆ lines │
│ --- ┆ --- │
│ str ┆ u32 │
╞═══════╪═══════╡
│ shop ┆ 11733 │
│ web ┆ 8495 │
└───────┴───────┘

How it works:

  1. then("web") made Polars look for a column called web and raise ColumnNotFoundError. pl.lit("web") is the constant text.
  2. group_by computes groups in parallel, so the order of shop and web can change between runs. sort("label") fixes it.
  3. The counts add up to all 20,228 lines, a quick check that no line was lost.

Alternative: map the values with replace_strict, which raises an error for any value that is not in the mapping. That makes it a data check too.

labeled = sales.with_columns(
label=pl.col("channel").replace_strict({"online": "web", "store": "shop"})
)
print(labeled["label"].value_counts().sort("label").rows())
Output
[('shop', 11733), ('web', 8495)]

M31-C01 · Category growth from 2023 to 2024

Section titled “M31-C01 · Category growth from 2023 to 2024”
Core

Compute the revenue per category for 2023 and 2024 as two columns, 2023 and 2024, rounded to whole dollars, and a column growth_pct (rounded to 1 decimal). Print the table sorted by growth, highest first.

Expected output
shape: (6, 4)
┌─────────────┬────────┬────────┬────────────┐
│ category ┆ 2023 ┆ 2024 ┆ growth_pct │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 │
╞═════════════╪════════╪════════╪════════════╡
│ Home ┆ 274450 ┆ 397845 ┆ 45 │
│ Beauty ┆ 64973 ┆ 85445 ┆ 31.5 │
│ Sports ┆ 244532 ┆ 299576 ┆ 22.5 │
│ Clothing ┆ 143987 ┆ 170700 ┆ 18.6 │
│ Books ┆ 49464 ┆ 57444 ┆ 16.1 │
│ Electronics ┆ 868183 ┆ 939925 ┆ 8.3 │
└─────────────┴────────┴────────┴────────────┘
Starter
# TODO: group by category and year, sum revenue, round to 0 decimals
# TODO: sort, then pivot the years into columns
# TODO: add growth_pct and sort by it, descending
Hint 1

group_by accepts keyword expressions as keys: group_by("category", year=pl.col("order_date").dt.year()).

Hint 2

After pivot(on="year", index="category", values="revenue") the new columns are named "2023" and "2024" (text). Use pl.col("2024").

Hint 3

Growth in percent is (new / old - 1) * 100.

Solution
growth = (
sales.group_by("category", year=pl.col("order_date").dt.year())
.agg(pl.col("revenue").sum().round(0))
.sort("category", "year")
.pivot(on="year", index="category", values="revenue")
.with_columns(growth_pct=((pl.col("2024") / pl.col("2023") - 1) * 100).round(1))
.sort("growth_pct", descending=True)
)
print(growth)
assert growth.columns == ["category", "2023", "2024", "growth_pct"]
assert growth.height == 6
Output
shape: (6, 4)
┌─────────────┬────────┬────────┬────────────┐
│ category ┆ 2023 ┆ 2024 ┆ growth_pct │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 │
╞═════════════╪════════╪════════╪════════════╡
│ Home ┆ 274450 ┆ 397845 ┆ 45 │
│ Beauty ┆ 64973 ┆ 85445 ┆ 31.5 │
│ Sports ┆ 244532 ┆ 299576 ┆ 22.5 │
│ Clothing ┆ 143987 ┆ 170700 ┆ 18.6 │
│ Books ┆ 49464 ┆ 57444 ┆ 16.1 │
│ Electronics ┆ 868183 ┆ 939925 ┆ 8.3 │
└─────────────┴────────┴────────┴────────────┘

How it works:

  1. The keyword key year= names the computed group column.
  2. Sorting by category and year before the pivot fixes the column order: 2023 comes before 2024.
  3. The pivot turns the integer years into column names, which are always strings.
  4. The final sort answers the question: which category grew fastest.

Alternative: compute both years with conditional sums in one group_by, with no pivot. filter inside agg restricts one aggregation to some rows.

year = pl.col("order_date").dt.year()
growth = (
sales.group_by("category")
.agg(
y2023=pl.col("revenue").filter(year == 2023).sum().round(0),
y2024=pl.col("revenue").filter(year == 2024).sum().round(0),
)
.with_columns(growth_pct=((pl.col("y2024") / pl.col("y2023") - 1) * 100).round(1))
.sort("growth_pct", descending=True)
)
print(growth["category"].to_list())
Output
['Home', 'Beauty', 'Sports', 'Clothing', 'Books', 'Electronics']

M31-C02 · Average order value per channel and year

Section titled “M31-C02 · Average order value per channel and year”
Core

The average order value (AOV) is the revenue divided by the number of orders, not by the number of lines. Compute the AOV per channel and year, rounded to 2 decimals, with the order count. Sort by channel, then year.

Expected output
shape: (4, 4)
┌─────────┬──────┬────────┬────────┐
│ channel ┆ year ┆ orders ┆ aov │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i32 ┆ u32 ┆ f64 │
╞═════════╪══════╪════════╪════════╡
│ online ┆ 2023 ┆ 2494 ┆ 249.74 │
│ online ┆ 2024 ┆ 3776 ┆ 237.45 │
│ store ┆ 2023 ┆ 4227 ┆ 241.95 │
│ store ┆ 2024 ┆ 4380 ┆ 240.71 │
└─────────┴──────┴────────┴────────┘
Starter
# TODO: group by channel and year
# TODO: aggregate revenue (sum) and orders (distinct order_id)
# TODO: add aov = revenue / orders, rounded to 2 decimals; sort
Hint 1

pl.col("order_id").n_unique() counts distinct orders. One order can have up to 3 lines.

Hint 2

Compute aov in a with_columns after agg, from the aggregated columns.

Solution
aov = (
sales.group_by("channel", year=pl.col("order_date").dt.year())
.agg(
revenue=pl.col("revenue").sum(),
orders=pl.col("order_id").n_unique(),
)
.with_columns(aov=(pl.col("revenue") / pl.col("orders")).round(2))
.select("channel", "year", "orders", "aov")
.sort("channel", "year")
)
print(aov)
assert aov.height == 4
assert aov["orders"].sum() == sales["order_id"].n_unique()
Output
shape: (4, 4)
┌─────────┬──────┬────────┬────────┐
│ channel ┆ year ┆ orders ┆ aov │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i32 ┆ u32 ┆ f64 │
╞═════════╪══════╪════════╪════════╡
│ online ┆ 2023 ┆ 2494 ┆ 249.74 │
│ online ┆ 2024 ┆ 3776 ┆ 237.45 │
│ store ┆ 2023 ┆ 4227 ┆ 241.95 │
│ store ┆ 2024 ┆ 4380 ┆ 240.71 │
└─────────┴──────┴────────┴────────┘

How it works:

  1. n_unique() counts each order once, even when it has three lines.
  2. The AOV is computed from the totals after the aggregation.
  3. The assert checks that each order belongs to exactly one channel and year: the four order counts add up to all 14,877 orders.

Alternative: first collapse the lines to one row per order, then average. This also gives the median order value, which revenue / orders cannot give.

per_order = sales.group_by(
"order_id", "channel", year=pl.col("order_date").dt.year()
).agg(pl.col("revenue").sum())
stats = (
per_order.group_by("channel", "year")
.agg(
aov=pl.col("revenue").mean().round(2),
median=pl.col("revenue").median().round(2),
)
.sort("channel", "year")
)
for row in stats.rows():
print(row)
Output
('online', 2023, 249.74, 108.41)
('online', 2024, 237.45, 119.47)
('store', 2023, 241.95, 116.96)
('store', 2024, 240.71, 119.98)
Core

Bigger stores sell more, so the operations team compares stores by revenue per square meter of floor area. Compute each store’s total revenue, join stores for city and size_sqm, and print the 5 stores with the highest per_sqm (rounded to 1 decimal). Validate that the join is one-to-one.

Expected output
shape: (5, 4)
┌──────────┬───────────────┬──────────┬─────────┐
│ store_id ┆ city ┆ size_sqm ┆ per_sqm │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ f64 │
╞══════════╪═══════════════╪══════════╪═════════╡
│ S10 ┆ Seattle ┆ 2480 ┆ 161.8 │
│ S03 ┆ Detroit ┆ 1420 ┆ 150.1 │
│ S01 ┆ Chicago ┆ 2850 ┆ 142.6 │
│ S11 ┆ San Francisco ┆ 1890 ┆ 142.2 │
│ S09 ┆ Philadelphia ┆ 1760 ┆ 139 │
└──────────┴───────────────┴──────────┴─────────┘
Starter
# TODO: total revenue per store_id
# TODO: join stores with validate="1:1"
# TODO: add per_sqm, sort descending, keep 5 rows and the columns shown
Hint 1

Aggregate first, then join. The aggregated table has one row per store, as does stores.

Hint 2

validate="1:1" raises an error if either side has a duplicate key.

Solution
per_store = sales.group_by("store_id").agg(pl.col("revenue").sum())
ranked = (
per_store.join(stores, on="store_id", how="inner", validate="1:1")
.with_columns(per_sqm=(pl.col("revenue") / pl.col("size_sqm")).round(1))
.sort("per_sqm", descending=True)
.select("store_id", "city", "size_sqm", "per_sqm")
.head(5)
)
print(ranked)
assert ranked.height == 5
assert ranked["per_sqm"].is_sorted(descending=True)
Output
shape: (5, 4)
┌──────────┬───────────────┬──────────┬─────────┐
│ store_id ┆ city ┆ size_sqm ┆ per_sqm │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ f64 │
╞══════════╪═══════════════╪══════════╪═════════╡
│ S10 ┆ Seattle ┆ 2480 ┆ 161.8 │
│ S03 ┆ Detroit ┆ 1420 ┆ 150.1 │
│ S01 ┆ Chicago ┆ 2850 ┆ 142.6 │
│ S11 ┆ San Francisco ┆ 1890 ┆ 142.2 │
│ S09 ┆ Philadelphia ┆ 1760 ┆ 139 │
└──────────┴───────────────┴──────────┴─────────┘

How it works:

  1. The aggregation shrinks 20,228 lines to 12 rows before the join, so the join is tiny.
  2. validate="1:1" proves that each store appears once on both sides.
  3. The ratio uses the totals, then the table is sorted and cut to 5 rows.

Alternative: join first and aggregate after. It gives the same numbers, but it joins every line, and you must list the store columns as group keys.

ranked = (
sales.join(stores, on="store_id", validate="m:1")
.group_by("store_id", "city", "size_sqm")
.agg(per_sqm=(pl.col("revenue").sum() / pl.col("size_sqm").first()).round(1))
.sort("per_sqm", descending=True)
.head(5)
)
print(ranked["store_id"].to_list())
Output
['S10', 'S03', 'S01', 'S11', 'S09']

M31-C04 · Stores with no Christmas orders

Section titled “M31-C04 · Stores with no Christmas orders”
Core

All stores are closed on 25 December, so every order on 2023-12-25 is an online order that some store fulfilled. List the stores that fulfilled no order that day, sorted by store id. Print how many lines were sold that day and the list.

Expected output
6 lines, channels: ['online']
shape: (8, 2)
┌──────────┬───────────────┐
│ store_id ┆ city │
│ --- ┆ --- │
│ str ┆ str │
╞══════════╪═══════════════╡
│ S01 ┆ Chicago │
│ S02 ┆ Minneapolis │
│ S04 ┆ Houston │
│ S05 ┆ Atlanta │
│ S06 ┆ Miami │
│ S08 ┆ Boston │
│ S11 ┆ San Francisco │
│ S12 ┆ Denver │
└──────────┴───────────────┘
Starter
# TODO: keep the sales lines of 2023-12-25
# TODO: anti join stores with them on store_id
# TODO: print the line count and the sorted store ids with cities
Hint 1

pl.date(2023, 12, 25) is a date literal you can compare with order_date.

Hint 2

stores.join(day, on="store_id", how="anti") keeps the stores that have no match in day.

Solution
day = sales.filter(pl.col("order_date") == pl.date(2023, 12, 25))
idle = stores.join(day, on="store_id", how="anti").sort("store_id")
print(day.height, "lines, channels:", day["channel"].unique().to_list())
print(idle.select("store_id", "city"))
assert idle.height + day["store_id"].n_unique() == stores.height
Output
6 lines, channels: ['online']
shape: (8, 2)
┌──────────┬───────────────┐
│ store_id ┆ city │
│ --- ┆ --- │
│ str ┆ str │
╞══════════╪═══════════════╡
│ S01 ┆ Chicago │
│ S02 ┆ Minneapolis │
│ S04 ┆ Houston │
│ S05 ┆ Atlanta │
│ S06 ┆ Miami │
│ S08 ┆ Boston │
│ S11 ┆ San Francisco │
│ S12 ┆ Denver │
└──────────┴───────────────┘

How it works:

  1. The filter keeps the 6 lines of Christmas Day 2023; all of them are online.
  2. The anti join keeps every store whose id does not appear among those lines.
  3. The assert checks the split: idle stores plus active stores make all 12 stores.

Alternative: use is_in with the list of active ids. It reads well for one small list; the anti join scales to large tables and to keys with several columns. In Polars 2, is_in(series) with a Series of the same dtype raises a DeprecationWarning (“ambiguous”); .implode() turns the Series into one list value, which is what is_in expects.

active_ids = day["store_id"].unique()
idle = stores.filter(~pl.col("store_id").is_in(active_ids.implode())).sort("store_id")
print(idle["store_id"].to_list())
Output
['S01', 'S02', 'S04', 'S05', 'S06', 'S08', 'S11', 'S12']

M31-C05 · Category share inside each region

Section titled “M31-C05 · Category share inside each region”
Core

Compute each category’s share of its region’s revenue, in percent with 1 decimal. Use a window expression for the region total. Print the rows for Books and Electronics, sorted by category and region.

Expected output
shape: (8, 3)
┌─────────────┬────────┬───────────┐
│ category ┆ region ┆ share_pct │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 │
╞═════════════╪════════╪═══════════╡
│ Books ┆ East ┆ 2.8 │
│ Books ┆ North ┆ 2.9 │
│ Books ┆ South ┆ 3.1 │
│ Books ┆ West ┆ 3 │
│ Electronics ┆ East ┆ 52.8 │
│ Electronics ┆ North ┆ 49 │
│ Electronics ┆ South ┆ 49.9 │
│ Electronics ┆ West ┆ 49 │
└─────────────┴────────┴───────────┘
Starter
# TODO: revenue per region and category
# TODO: share_pct = revenue / region total * 100, with .over("region")
# TODO: keep Books and Electronics; sort by category, region
Hint 1

Aggregate first with group_by("region", "category"). Then pl.col("revenue").sum().over("region") is the region total on every row.

Hint 2

pl.col("category").is_in(["Books", "Electronics"]) keeps the two categories.

Solution
shares = (
sales.group_by("region", "category")
.agg(pl.col("revenue").sum())
.with_columns(
share_pct=(
100 * pl.col("revenue") / pl.col("revenue").sum().over("region")
).round(1)
)
.filter(pl.col("category").is_in(["Books", "Electronics"]))
.sort("category", "region")
.select("category", "region", "share_pct")
)
print(shares)
assert shares.height == 8
assert shares.filter(pl.col("category") == "Electronics")["share_pct"].min() > 45
Output
shape: (8, 3)
┌─────────────┬────────┬───────────┐
│ category ┆ region ┆ share_pct │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 │
╞═════════════╪════════╪═══════════╡
│ Books ┆ East ┆ 2.8 │
│ Books ┆ North ┆ 2.9 │
│ Books ┆ South ┆ 3.1 │
│ Books ┆ West ┆ 3 │
│ Electronics ┆ East ┆ 52.8 │
│ Electronics ┆ North ┆ 49 │
│ Electronics ┆ South ┆ 49.9 │
│ Electronics ┆ West ┆ 49 │
└─────────────┴────────┴───────────┘

How it works:

  1. After the group_by, each row is one region and category.
  2. sum().over("region") adds the six category totals of each region and writes the result to each of its rows.
  3. The filter runs after the window, so the region totals still include all six categories.

Alternative: compute the region totals with a second group_by and join them back. It needs two steps and a join where over needs one expression.

cat = sales.group_by("region", "category").agg(pl.col("revenue").sum())
totals = cat.group_by("region").agg(region_total=pl.col("revenue").sum())
joined = cat.join(totals, on="region", validate="m:1").with_columns(
share_pct=(100 * pl.col("revenue") / pl.col("region_total")).round(1)
)
print(
joined.filter(pl.col("category") == "Books").sort("region")["share_pct"].to_list()
)
Output
[2.8, 2.9, 3.1, 3.0]

M31-C06 · When did Denver pass 50,000 USD?

Section titled “M31-C06 · When did Denver pass 50,000 USD?”
Core

Store S12 (Denver) opened on 2023-06-15. Compute its daily revenue, then a running total in date order, and find the first day on which the running total reached 50,000 USD. Print its first sales day and that day with the running total rounded to 2 decimals.

Expected output
first sale: 2023-06-15
passed 50k: 2023-11-23 50085.21
Starter
# TODO: daily revenue of S12, sorted by date
# TODO: running total with cum_sum
# TODO: first row where the running total >= 50_000
Hint 1

cum_sum() depends on row order. Sort by order_date first.

Hint 2

filter(pl.col("running") >= 50_000).head(1) keeps the first qualifying day of a sorted table.

Solution
denver = (
sales.filter(pl.col("store_id") == "S12")
.group_by("order_date")
.agg(pl.col("revenue").sum())
.sort("order_date")
.with_columns(running=pl.col("revenue").cum_sum())
)
passed = denver.filter(pl.col("running") >= 50_000).head(1)
print("first sale:", denver["order_date"][0])
print("passed 50k:", passed["order_date"][0], round(passed["running"][0], 2))
assert denver["order_date"][0].isoformat() == "2023-06-15"
assert passed["running"][0] >= 50_000
Output
first sale: 2023-06-15
passed 50k: 2023-11-23 50085.21

How it works:

  1. The daily group_by is sorted by date, so cum_sum adds the days in time order.
  2. The filter keeps every day at or above 50,000; the first of them is the answer.
  3. Indexing a Series with [0] returns a Python date or float.

Alternative: compute the running total per store for all stores at once with a window that has its own order, then pick S12. order_by= sorts inside each window, whatever the row order of the table.

daily = sales.group_by("store_id", "order_date").agg(pl.col("revenue").sum())
running = daily.with_columns(
running=pl.col("revenue").cum_sum().over("store_id", order_by="order_date")
)
first = (
running.filter(pl.col("running") >= 50_000)
.group_by("store_id")
.agg(pl.col("order_date").min())
)
print(first.filter(pl.col("store_id") == "S12")["order_date"][0])
Output
2023-11-23
Core

Write a lazy query that answers “how many units of each product launched in 2022 or later were sold?”. Scan both CSV files, join, filter on launch_date, aggregate the quantity and sort by product id. Then print only the plan lines that contain PROJECT or SELECTION (stripped of spaces), followed by the collected result.

Expected output
PROJECT 2/13 COLUMNS
PROJECT 2/6 COLUMNS
SELECTION: col("launch_date") >= 2022-01-01
shape: (8, 2)
┌────────────┬───────┐
│ product_id ┆ units │
│ --- ┆ --- │
│ str ┆ i64 │
╞════════════╪═══════╡
│ P004 ┆ 599 │
│ P005 ┆ 842 │
│ P007 ┆ 457 │
│ P019 ┆ 954 │
│ P020 ┆ 579 │
│ P023 ┆ 697 │
│ P025 ┆ 411 │
│ P029 ┆ 749 │
└────────────┴───────┘
Starter
query = (
pl.scan_csv("data/sales.csv")
# TODO: join pl.scan_csv("data/products.csv", try_parse_dates=True)
# TODO: filter launch_date >= 2022-01-01
# TODO: group by product_id, sum quantity as units, sort by product_id
)
# TODO: print the PROJECT and SELECTION lines of query.explain()
# TODO: print query.collect()
Hint 1

query.explain() returns one string. .splitlines() splits it into lines.

Hint 2

Join with on="product_id". The filter uses a column of products, so the optimizer can push it into the products scan.

Solution
query = (
pl.scan_csv("data/sales.csv")
.join(pl.scan_csv("data/products.csv", try_parse_dates=True), on="product_id")
.filter(pl.col("launch_date") >= pl.date(2022, 1, 1))
.group_by("product_id")
.agg(units=pl.col("quantity").sum())
.sort("product_id")
)
for line in query.explain().splitlines():
if "PROJECT" in line or "SELECTION" in line:
print(line.strip())
result = query.collect()
print(result)
assert result.height == 8
assert result["units"].min() > 0
Output
PROJECT 2/13 COLUMNS
PROJECT 2/6 COLUMNS
SELECTION: col("launch_date") >= 2022-01-01
shape: (8, 2)
┌────────────┬───────┐
│ product_id ┆ units │
│ --- ┆ --- │
│ str ┆ i64 │
╞════════════╪═══════╡
│ P004 ┆ 599 │
│ P005 ┆ 842 │
│ P007 ┆ 457 │
│ P019 ┆ 954 │
│ P020 ┆ 579 │
│ P023 ┆ 697 │
│ P025 ┆ 411 │
│ P029 ┆ 749 │
└────────────┴───────┘

How it works:

  1. The sales scan reads only product_id and quantity: 2 of 13 columns.
  2. The products scan reads product_id and launch_date, and the date filter runs inside it. Only 8 product rows reach the join.
  3. The inner join then drops all sales lines of older products, before the aggregation.

Alternative: use a semi join, which says “keep the sales lines of these products” directly and adds no product columns.

new_products = pl.scan_csv("data/products.csv", try_parse_dates=True).filter(
pl.col("launch_date") >= pl.date(2022, 1, 1)
)
units = (
pl.scan_csv("data/sales.csv")
.join(new_products, on="product_id", how="semi")
.group_by("product_id")
.agg(units=pl.col("quantity").sum())
.sort("product_id")
.collect()
)
print(units.height, units["units"].sum())
Output
8 5288

M31-C08 · Port a pandas summary to Polars

Section titled “M31-C08 · Port a pandas summary to Polars”
Core

Refactor: rewrite this pandas summary in Polars. For each region it computes the online share of lines and the mean discount of online lines (in percent), rounded to 3 and 2 decimals. Print the Polars result sorted by region and check it against the pandas numbers.

pandas version
import pandas as pd
df = pd.read_csv("data/sales.csv")
df["is_online"] = df["channel"] == "online"
summary = df.groupby("region").agg(online_share=("is_online", "mean")).round(3)
online = df[df["is_online"]]
summary["online_discount_pct"] = (
online.groupby("region")["discount"].mean() * 100
).round(2)
print(summary.reset_index())
Expected output
shape: (4, 3)
┌────────┬──────────────┬─────────────────────┐
│ region ┆ online_share ┆ online_discount_pct │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞════════╪══════════════╪═════════════════════╡
│ East ┆ 0.422 ┆ 3.7 │
│ North ┆ 0.432 ┆ 3.16 │
│ South ┆ 0.413 ┆ 3.56 │
│ West ┆ 0.413 ┆ 3.36 │
└────────┴──────────────┴─────────────────────┘
Starter
# TODO: one group_by("region").agg(...) with two expressions
# Use (pl.col("channel") == "online").mean() for the share
# Use pl.col("discount").filter(...).mean() for the online discount
Hint 1

The mean of a Boolean column is the share of true values.

Hint 2

.filter() inside agg restricts one expression to some rows of the group: pl.col("discount").filter(pl.col("channel") == "online").mean().

Solution
import pandas as pd
is_online = pl.col("channel") == "online"
summary = (
sales.group_by("region")
.agg(
online_share=is_online.mean().round(3),
online_discount_pct=(pl.col("discount").filter(is_online).mean() * 100).round(
2
),
)
.sort("region")
)
print(summary)
df = pd.read_csv("data/sales.csv")
df["is_online"] = df["channel"] == "online"
expected = df.groupby("region").agg(online_share=("is_online", "mean")).round(3)
online = df[df["is_online"]]
expected["online_discount_pct"] = (
online.groupby("region")["discount"].mean() * 100
).round(2)
assert summary.equals(pl.from_pandas(expected.reset_index()))
Output
shape: (4, 3)
┌────────┬──────────────┬─────────────────────┐
│ region ┆ online_share ┆ online_discount_pct │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞════════╪══════════════╪═════════════════════╡
│ East ┆ 0.422 ┆ 3.7 │
│ North ┆ 0.432 ┆ 3.16 │
│ South ┆ 0.413 ┆ 3.56 │
│ West ┆ 0.413 ┆ 3.36 │
└────────┴──────────────┴─────────────────────┘

How it works:

  1. The pandas code needs a helper column, a second filtered DataFrame and an assignment that aligns on the index. The Polars version is one group_by with two expressions.
  2. is_online is an expression stored in a variable, used twice.
  3. filter inside agg works per group: it keeps only the online lines of each region before the mean.
  4. from_pandas turns the pandas result into Polars, and equals compares names and values.

Alternative: write the share as a sum divided by a count. It is longer but shows what the Boolean mean does.

summary = (
sales.group_by("region")
.agg(
online_share=((pl.col("channel") == "online").sum() / pl.len()).round(3)
)
.sort("region")
)
print(summary["online_share"].to_list())
Output
[0.422, 0.432, 0.413, 0.413]

M31-C09 · Replace a row loop with expressions

Section titled “M31-C09 · Replace a row loop with expressions”
Core

Refactor: this loop computes the gross profit per category for discounted lines. It walks over 20,000 rows in Python and looks up each cost in a dict. Rewrite it with a join, a filter and a group_by. Print the result sorted by gross profit, highest first, rounded to 2 decimals, and check it against the loop.

Loop version
cost = dict(products.select("product_id", "unit_cost").iter_rows())
profit: dict[str, float] = {}
for row in sales.iter_rows(named=True):
if row["discount"] > 0:
gp = row["revenue"] - cost[row["product_id"]] * row["quantity"]
profit[row["category"]] = profit.get(row["category"], 0.0) + gp
Expected output
shape: (6, 2)
┌─────────────┬──────────────┐
│ category ┆ gross_profit │
│ --- ┆ --- │
│ str ┆ f64 │
╞═════════════╪══════════════╡
│ Electronics ┆ 193228.66 │
│ Home ┆ 107169.15 │
│ Sports ┆ 85585.75 │
│ Clothing ┆ 58558.34 │
│ Beauty ┆ 28933.44 │
│ Books ┆ 20662.19 │
└─────────────┴──────────────┘
Starter
# TODO: join the unit_cost onto sales (validate m:1)
# TODO: keep discounted lines, compute gross profit, sum per category
# TODO: round, sort descending, print; compare with the loop result
Hint 1

sales.join(products.select("product_id", "unit_cost"), on="product_id", validate="m:1") adds the cost to every line.

Hint 2

Write the gross profit as one expression inside agg: (pl.col("revenue") - pl.col("unit_cost") * pl.col("quantity")).sum().

Solution
import math
fast = (
sales.join(
products.select("product_id", "unit_cost"), on="product_id", validate="m:1"
)
.filter(pl.col("discount") > 0)
.group_by("category")
.agg(
gross_profit=(pl.col("revenue") - pl.col("unit_cost") * pl.col("quantity"))
.sum()
.round(2)
)
.sort("gross_profit", descending=True)
)
print(fast)
cost = dict(products.select("product_id", "unit_cost").iter_rows())
profit: dict[str, float] = {}
for row in sales.iter_rows(named=True):
if row["discount"] > 0:
gp = row["revenue"] - cost[row["product_id"]] * row["quantity"]
profit[row["category"]] = profit.get(row["category"], 0.0) + gp
for category, value in fast.iter_rows():
assert math.isclose(profit[category], value, abs_tol=0.01)
Output
shape: (6, 2)
┌─────────────┬──────────────┐
│ category ┆ gross_profit │
│ --- ┆ --- │
│ str ┆ f64 │
╞═════════════╪══════════════╡
│ Electronics ┆ 193228.66 │
│ Home ┆ 107169.15 │
│ Sports ┆ 85585.75 │
│ Clothing ┆ 58558.34 │
│ Beauty ┆ 28933.44 │
│ Books ┆ 20662.19 │
└─────────────┴──────────────┘

How it works:

  1. The join replaces the dict lookup; validate="m:1" guarantees one cost per product.
  2. The filter replaces the if; the expression in agg replaces the loop body and the running sum.
  3. The loop and the expressions add the floats in a different order, so the totals can differ in the last digits. The assert compares them with math.isclose and a tolerance of 1 cent.

Alternative: compute the gross profit as a column first. The extra column helps when several later steps need it.

lines = sales.join(
products.select("product_id", "unit_cost"), on="product_id", validate="m:1"
).with_columns(
gross_profit=pl.col("revenue") - pl.col("unit_cost") * pl.col("quantity")
)
top = (
lines.filter(pl.col("discount") > 0)
.group_by("category")
.agg(pl.col("gross_profit").sum())
.sort("gross_profit", descending=True)
)
print(top["category"].to_list())
Output
['Electronics', 'Home', 'Sports', 'Clothing', 'Beauty', 'Books']

M31-C10 · A month by channel table for Q4 2024

Section titled “M31-C10 · A month by channel table for Q4 2024”
Core

Count the sales lines per month and channel for October to December 2024. Show it as a wide table with one row per month (2024-10, …) and the columns store and online, in that order. Then add an online_pct column (rounded to 1 decimal).

Expected output
shape: (3, 4)
┌─────────┬───────┬────────┬────────────┐
│ month ┆ store ┆ online ┆ online_pct │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ u32 ┆ f64 │
╞═════════╪═══════╪════════╪════════════╡
│ 2024-10 ┆ 482 ┆ 436 ┆ 47.5 │
│ 2024-11 ┆ 637 ┆ 752 ┆ 54.1 │
│ 2024-12 ┆ 816 ┆ 851 ┆ 51 │
└─────────┴───────┴────────┴────────────┘
Starter
# TODO: filter Q4 2024, add month = order_date formatted as "%Y-%m"
# TODO: count lines per month and channel
# TODO: pivot with on="channel"; choose the column order with on_columns
# TODO: add online_pct; sort by month
Hint 1

pl.col("order_date").dt.strftime("%Y-%m") gives the month as text. is_between(pl.date(2024, 10, 1), pl.date(2024, 12, 31)) keeps Q4.

Hint 2

The on_columns parameter of pivot takes the list of new columns, in the order you want them.

Solution
q4 = sales.filter(
pl.col("order_date").is_between(pl.date(2024, 10, 1), pl.date(2024, 12, 31))
)
table = (
q4.group_by(
month=pl.col("order_date").dt.strftime("%Y-%m"), channel=pl.col("channel")
)
.agg(lines=pl.len())
.pivot(on="channel", on_columns=["store", "online"], index="month", values="lines")
.with_columns(
online_pct=(
100 * pl.col("online") / (pl.col("online") + pl.col("store"))
).round(1)
)
.sort("month")
)
print(table)
assert table.columns == ["month", "store", "online", "online_pct"]
assert (table["store"] + table["online"]).sum() == q4.height
Output
shape: (3, 4)
┌─────────┬───────┬────────┬────────────┐
│ month ┆ store ┆ online ┆ online_pct │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ u32 ┆ f64 │
╞═════════╪═══════╪════════╪════════════╡
│ 2024-10 ┆ 482 ┆ 436 ┆ 47.5 │
│ 2024-11 ┆ 637 ┆ 752 ┆ 54.1 │
│ 2024-12 ┆ 816 ┆ 851 ┆ 51 │
└─────────┴───────┴────────┴────────────┘

How it works:

  1. is_between includes both end dates by default.
  2. on_columns lists the new columns and their order, so the result does not depend on which channel appears first.
  3. The row order still comes from the unsorted group_by, so the final sort("month") is needed.

Alternative: skip the pivot and compute the counts with conditional sums. The mean of a Boolean gives the share directly.

table = (
q4.group_by(month=pl.col("order_date").dt.strftime("%Y-%m"))
.agg(
store=(pl.col("channel") == "store").sum(),
online=(pl.col("channel") == "online").sum(),
online_pct=((pl.col("channel") == "online").mean() * 100).round(1),
)
.sort("month")
)
print(table.rows())
Output
[('2024-10', 482, 436, 47.5), ('2024-11', 637, 752, 54.1), ('2024-12', 816, 851, 51.0)]

M31-C11 · Do weekends shift the channel mix?

Section titled “M31-C11 · Do weekends shift the channel mix?”
Core

Interpret a result: a manager believes that customers shop online more on weekends. Compute the online share of lines for weekdays and for weekends (Saturday and Sunday), rounded to 3 decimals, the number of lines in each group and the lines per calendar day (1 decimal). Print the table, then one sentence that states the difference in percentage points and whether it supports the belief (use a threshold of 2 points).

Expected output
shape: (2, 5)
┌─────────┬──────────────┬───────┬──────┬─────────┐
│ weekend ┆ online_share ┆ lines ┆ days ┆ per_day │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ bool ┆ f64 ┆ u32 ┆ u32 ┆ f64 │
╞═════════╪══════════════╪═══════╪══════╪═════════╡
│ false ┆ 0.421 ┆ 13262 ┆ 522 ┆ 25.4 │
│ true ┆ 0.418 ┆ 6966 ┆ 209 ┆ 33.3 │
└─────────┴──────────────┴───────┴──────┴─────────┘
Weekend minus weekday: -0.3 points; this does not support the belief.
Starter
# TODO: add weekend = weekday() >= 6
# TODO: online share and line count per weekend flag, sorted
# TODO: difference in percentage points; print the sentence
Hint 1

pl.col("order_date").dt.weekday() >= 6 is true for Saturday (6) and Sunday (7).

Hint 2

pl.col("order_date").n_unique() counts the calendar days in a group. A percentage point is the unit of a difference between two percentages: 42.1% − 41.8% = 0.3 points.

Solution
mix = (
sales.group_by(weekend=pl.col("order_date").dt.weekday() >= 6)
.agg(
online_share=(pl.col("channel") == "online").mean().round(3),
lines=pl.len(),
days=pl.col("order_date").n_unique(),
)
.with_columns(per_day=(pl.col("lines") / pl.col("days")).round(1))
.sort("weekend")
)
print(mix)
weekday_share, weekend_share = mix["online_share"].to_list()
diff_pp = round((weekend_share - weekday_share) * 100, 1)
verdict = "supports" if diff_pp >= 2 else "does not support"
print(f"Weekend minus weekday: {diff_pp} points; this {verdict} the belief.")
assert abs(diff_pp) < 2
Output
shape: (2, 5)
┌─────────┬──────────────┬───────┬──────┬─────────┐
│ weekend ┆ online_share ┆ lines ┆ days ┆ per_day │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ bool ┆ f64 ┆ u32 ┆ u32 ┆ f64 │
╞═════════╪══════════════╪═══════╪══════╪═════════╡
│ false ┆ 0.421 ┆ 13262 ┆ 522 ┆ 25.4 │
│ true ┆ 0.418 ┆ 6966 ┆ 209 ┆ 33.3 │
└─────────┴──────────────┴───────┴──────┴─────────┘
Weekend minus weekday: -0.3 points; this does not support the belief.

How it works:

  1. The group key is a Boolean expression named weekend; sorting puts false before true.
  2. Both groups have about 42% online lines. The difference is a fraction of a point and slightly negative.
  3. Interpretation: the channel mix does not depend on the day type. Weekend days have more lines per day (the per_day column), but online and store sales grow together. The belief is not supported.

Alternative: look at every weekday, not only the two groups. The daily shares run from 37.5% (Tuesday) to 45.1% (Monday): there is day-to-day noise, but Saturday and Sunday sit in the middle.

by_day = (
sales.group_by(weekday=pl.col("order_date").dt.weekday())
.agg(online_share=(pl.col("channel") == "online").mean().round(3))
.sort("weekday")
)
print(by_day["online_share"].to_list())
Output
[0.451, 0.375, 0.423, 0.406, 0.441, 0.421, 0.415]

M31-C12 · Choose between an inner join and a semi join

Section titled “M31-C12 · Choose between an inner join and a semi join”
Core

Choose a method and justify it: list the stores (id and city) that sold at least one bulk line (quantity >= 10). Write it once with an inner join plus unique, once with a semi join. Print the semi-join result sorted by store id, then the number of rows the inner join produced before unique. Say which method you choose and why.

Expected output
shape: (10, 2)
┌──────────┬───────────────┐
│ store_id ┆ city │
│ --- ┆ --- │
│ str ┆ str │
╞══════════╪═══════════════╡
│ S01 ┆ Chicago │
│ S02 ┆ Minneapolis │
│ S03 ┆ Detroit │
│ S04 ┆ Houston │
│ S05 ┆ Atlanta │
│ S07 ┆ New York │
│ S09 ┆ Philadelphia │
│ S10 ┆ Seattle │
│ S11 ┆ San Francisco │
│ S12 ┆ Denver │
└──────────┴───────────────┘
inner join rows before unique: 29
Starter
bulk = sales.filter(pl.col("quantity") >= 10)
# TODO: version A: stores.join(bulk, ...) then select + unique + sort
# TODO: version B: stores.join(bulk, ..., how="semi") + sort
# TODO: print version B, then the row count of the inner join before unique
Hint 1

The inner join repeats a store once per matching bulk line.

Hint 2

A semi join keeps each left row once, with only the left columns.

Solution
bulk = sales.filter(pl.col("quantity") >= 10)
inner = stores.join(bulk, on="store_id", how="inner")
version_a = inner.select("store_id", "city").unique().sort("store_id")
version_b = stores.join(bulk, on="store_id", how="semi").select("store_id", "city")
version_b = version_b.sort("store_id")
print(version_b)
print("inner join rows before unique:", inner.height)
assert version_a.equals(version_b)
Output
shape: (10, 2)
┌──────────┬───────────────┐
│ store_id ┆ city │
│ --- ┆ --- │
│ str ┆ str │
╞══════════╪═══════════════╡
│ S01 ┆ Chicago │
│ S02 ┆ Minneapolis │
│ S03 ┆ Detroit │
│ S04 ┆ Houston │
│ S05 ┆ Atlanta │
│ S07 ┆ New York │
│ S09 ┆ Philadelphia │
│ S10 ┆ Seattle │
│ S11 ┆ San Francisco │
│ S12 ┆ Denver │
└──────────┴───────────────┘
inner join rows before unique: 29

How it works:

  1. Both versions give the same 10 stores.
  2. The inner join first builds one row per bulk line (29 rows with 17 columns), then unique throws most of them away.
  3. Choose the semi join. It states the question directly (“stores that have a match”), never duplicates rows and does not carry the sales columns. On a large fact table, the inner join can produce millions of rows only to discard them.

M31-X01 · The runner-up category of each month

Section titled “M31-X01 · The runner-up category of each month”
Challenge

Electronics has the largest gross profit in every month of 2024. The buying team wants the runner-up: for each month of 2024, the category with the second-largest gross profit, its gross profit (2 decimals) and its margin (3 decimals). Build the pipeline lazily from the two CSV files, collect once and print the 12 rows in month order. Then print the months in which the runner-up was not Home.

Expected output
shape: (12, 4)
┌───────┬──────────┬──────────────┬────────┐
│ month ┆ category ┆ gross_profit ┆ margin │
│ --- ┆ --- ┆ --- ┆ --- │
│ i8 ┆ str ┆ f64 ┆ f64 │
╞═══════╪══════════╪══════════════╪════════╡
│ 1 ┆ Home ┆ 12141.59 ┆ 0.567 │
│ 2 ┆ Home ┆ 13472.21 ┆ 0.572 │
│ 3 ┆ Home ┆ 15525.31 ┆ 0.552 │
│ 4 ┆ Home ┆ 15156.18 ┆ 0.549 │
│ 5 ┆ Home ┆ 14560.25 ┆ 0.559 │
│ 6 ┆ Sports ┆ 20979.09 ┆ 0.579 │
│ 7 ┆ Sports ┆ 18575.2 ┆ 0.581 │
│ 8 ┆ Sports ┆ 18138.1 ┆ 0.578 │
│ 9 ┆ Home ┆ 16384.04 ┆ 0.546 │
│ 10 ┆ Home ┆ 25112.93 ┆ 0.553 │
│ 11 ┆ Home ┆ 29646.12 ┆ 0.542 │
│ 12 ┆ Home ┆ 28953.13 ┆ 0.546 │
└───────┴──────────┴──────────────┴────────┘
[6, 7, 8]
Starter
lines = (
pl.scan_csv("data/sales.csv", try_parse_dates=True)
# TODO: join the unit_cost from data/products.csv (m:1)
# TODO: keep 2024; add month (1-12) and gross_profit
)
# TODO: per month and category: gross_profit and revenue sums
# TODO: rank gross_profit inside each month; keep rank 2
# TODO: margin = gross_profit / revenue; sort by month; collect
Hint 1

pl.col("gross_profit").rank("ordinal", descending=True).over("month") numbers the categories of each month from 1.

Hint 2

Compute the margin from the monthly sums, not from the lines. Round only at the end.

Hint 3

Only call collect() once, after the last sort.

Solution
costs = pl.scan_csv("data/products.csv").select("product_id", "unit_cost")
runner_up = (
pl.scan_csv("data/sales.csv", try_parse_dates=True)
.join(costs, on="product_id", how="left", validate="m:1")
.filter(pl.col("order_date").dt.year() == 2024)
.with_columns(
month=pl.col("order_date").dt.month(),
gross_profit=pl.col("revenue") - pl.col("unit_cost") * pl.col("quantity"),
)
.group_by("month", "category")
.agg(pl.col("gross_profit").sum(), pl.col("revenue").sum())
.filter(pl.col("gross_profit").rank("ordinal", descending=True).over("month") == 2)
.with_columns(
margin=(pl.col("gross_profit") / pl.col("revenue")).round(3),
gross_profit=pl.col("gross_profit").round(2),
)
.select("month", "category", "gross_profit", "margin")
.sort("month")
.collect()
)
with pl.Config(tbl_rows=12):
print(runner_up)
print(runner_up.filter(pl.col("category") != "Home")["month"].to_list())
assert runner_up.height == 12
assert runner_up["month"].to_list() == list(range(1, 13))
Output
shape: (12, 4)
┌───────┬──────────┬──────────────┬────────┐
│ month ┆ category ┆ gross_profit ┆ margin │
│ --- ┆ --- ┆ --- ┆ --- │
│ i8 ┆ str ┆ f64 ┆ f64 │
╞═══════╪══════════╪══════════════╪════════╡
│ 1 ┆ Home ┆ 12141.59 ┆ 0.567 │
│ 2 ┆ Home ┆ 13472.21 ┆ 0.572 │
│ 3 ┆ Home ┆ 15525.31 ┆ 0.552 │
│ 4 ┆ Home ┆ 15156.18 ┆ 0.549 │
│ 5 ┆ Home ┆ 14560.25 ┆ 0.559 │
│ 6 ┆ Sports ┆ 20979.09 ┆ 0.579 │
│ 7 ┆ Sports ┆ 18575.2 ┆ 0.581 │
│ 8 ┆ Sports ┆ 18138.1 ┆ 0.578 │
│ 9 ┆ Home ┆ 16384.04 ┆ 0.546 │
│ 10 ┆ Home ┆ 25112.93 ┆ 0.553 │
│ 11 ┆ Home ┆ 29646.12 ┆ 0.542 │
│ 12 ┆ Home ┆ 28953.13 ┆ 0.546 │
└───────┴──────────┴──────────────┴────────┘
[6, 7, 8]

How it works:

  1. The pipeline is one lazy chain. The optimizer reads only the columns it needs and pushes the year filter into the sales scan.
  2. The filter with a window keeps the rank-2 category of each month without a separate ranking column.
  3. The margin is computed after both sums, then the gross profit is rounded. The order matters: rounding first would change the margin slightly.
  4. pl.Config(tbl_rows=12) shows all 12 rows for this one print.
  5. Interpretation: Home is the runner-up most of the year, but Sports takes second place in June, July and August (the printed list [6, 7, 8]). That matches the summer peak of Sports in the data dictionary.

Alternative: sort the categories inside each month and take the second one with sort_by(...).get(1) in agg. It gives the same months, but the rank-and-filter form reads more clearly and extends to “top 3”.

per_month = (
pl.scan_csv("data/sales.csv", try_parse_dates=True)
.join(costs, on="product_id", how="left", validate="m:1")
.filter(pl.col("order_date").dt.year() == 2024)
.group_by(month=pl.col("order_date").dt.month(), category=pl.col("category"))
.agg(
gross_profit=(
pl.col("revenue") - pl.col("unit_cost") * pl.col("quantity")
).sum()
)
.group_by("month")
.agg(pl.col("category").sort_by("gross_profit", descending=True).get(1))
.sort("month")
.collect()
)
print(per_month.filter(pl.col("category") != "Home")["month"].to_list())
assert per_month["category"].to_list() == runner_up["category"].to_list()
Output
[6, 7, 8]

M31-X02 · Repeat customers and first-purchase cohorts

Section titled “M31-X02 · Repeat customers and first-purchase cohorts”
Challenge

A cohort is a group of customers who share a start date, here the quarter of their first order. Using only sales, compute for each customer the first order date, the number of distinct orders and whether they ordered in both 2023 and 2024. Print: the number of customers, the share who bought in both years (3 decimals) and the mean number of orders (2 decimals). Then print, for each first-order quarter of 2023, the number of customers and how many of them signed up before 2023 (the signup_date in data/customers.csv), with that share in percent (1 decimal).

Expected output
3254 0.468 4.57
shape: (4, 4)
┌─────────┬───────────────┬───────────────┬───────────┐
│ cohort ┆ new_customers ┆ signed_before ┆ older_pct │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ u32 ┆ f64 │
╞═════════╪═══════════════╪═══════════════╪═══════════╡
│ 2023-Q1 ┆ 731 ┆ 674 ┆ 92.2 │
│ 2023-Q2 ┆ 499 ┆ 359 ┆ 71.9 │
│ 2023-Q3 ┆ 335 ┆ 175 ┆ 52.2 │
│ 2023-Q4 ┆ 358 ┆ 133 ┆ 37.2 │
└─────────┴───────────────┴───────────────┴───────────┘
Starter
customers = (
sales.group_by("customer_id")
# TODO: first order date, distinct orders, distinct years
)
# TODO: print the three headline numbers
# TODO: new customers per quarter of the first order, for 2023 only
# TODO: join signup_date from data/customers.csv; count signups before 2023
Hint 1

pl.col("order_date").dt.year().n_unique() is 2 for a customer who bought in both years.

Hint 2

Build the quarter label with pl.format, which fills each {} with the next expression. Join customer_id and signup_date from data/customers.csv with validate="1:1".

Solution
customers = sales.group_by("customer_id").agg(
first=pl.col("order_date").min(),
orders=pl.col("order_id").n_unique(),
years=pl.col("order_date").dt.year().n_unique(),
)
both_share = round((customers["years"] == 2).mean(), 3)
print(customers.height, both_share, round(customers["orders"].mean(), 2))
signups = pl.read_csv("data/customers.csv", try_parse_dates=True).select(
"customer_id", "signup_date"
)
quarter = pl.format("{}-Q{}", pl.col("first").dt.year(), pl.col("first").dt.quarter())
cohorts = (
customers.filter(pl.col("first").dt.year() == 2023)
.join(signups, on="customer_id", how="left", validate="1:1")
.group_by(cohort=quarter)
.agg(
new_customers=pl.len(),
signed_before=(pl.col("signup_date") < pl.date(2023, 1, 1)).sum(),
)
.with_columns(
older_pct=(100 * pl.col("signed_before") / pl.col("new_customers")).round(1)
)
.sort("cohort")
)
print(cohorts)
assert customers.height == 3254
assert (
cohorts["new_customers"].sum()
== customers.filter(pl.col("first").dt.year() == 2023).height
)
Output
3254 0.468 4.57
shape: (4, 4)
┌─────────┬───────────────┬───────────────┬───────────┐
│ cohort ┆ new_customers ┆ signed_before ┆ older_pct │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ u32 ┆ f64 │
╞═════════╪═══════════════╪═══════════════╪═══════════╡
│ 2023-Q1 ┆ 731 ┆ 674 ┆ 92.2 │
│ 2023-Q2 ┆ 499 ┆ 359 ┆ 71.9 │
│ 2023-Q3 ┆ 335 ┆ 175 ┆ 52.2 │
│ 2023-Q4 ┆ 358 ┆ 133 ┆ 37.2 │
└─────────┴───────────────┴───────────────┴───────────┘

How it works:

  1. One group_by collapses 20,228 lines to 3,254 customers with three facts each.
  2. customers["years"] == 2 is a Boolean Series; its mean is the share of customers who bought in both years.
  3. The cohort label is built with pl.format. The join adds each customer’s signup date, and the Boolean sum counts the signups before 2023 in each cohort.
  4. Interpretation: every 2023 cohort holds many customers who signed up before 2023 (the older_pct column), most of all 2023-Q1. This is left censoring: the sales data starts in the middle of the customers’ history, so a first purchase in the data is not the same as a new customer.

Alternative: mark each line of a customer’s first order day with a window. This keeps the line-level table, which helps when you also want the first order’s revenue. Every customer appears, so the count equals the 3,254 above.

first_lines = sales.filter(
pl.col("order_date") == pl.col("order_date").min().over("customer_id")
)
print(first_lines["customer_id"].n_unique())
Output
3254

M31-X03 · Which categories are bought together?

Section titled “M31-X03 · Which categories are bought together?”
Challenge

A market basket question: which pairs of categories appear together in the same order most often? Build every pair of distinct categories within each order (each pair once, in alphabetical order), count the orders per pair and print the top 5. Sort ties by the category names so the output is fixed.

Expected output
shape: (5, 3)
┌─────────────┬─────────────┬────────┐
│ category ┆ category_b ┆ orders │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ u32 │
╞═════════════╪═════════════╪════════╡
│ Clothing ┆ Electronics ┆ 488 │
│ Clothing ┆ Sports ┆ 441 │
│ Electronics ┆ Sports ┆ 407 │
│ Beauty ┆ Clothing ┆ 404 │
│ Clothing ┆ Home ┆ 392 │
└─────────────┴─────────────┴────────┘
orders with 2+ categories: 3675
Starter
order_cats = sales.select("order_id", "category").unique()
# TODO: join order_cats with itself on order_id
# TODO: keep pairs where category < category_b
# TODO: count orders per pair; sort by count desc, then names; top 5
Hint 1

A self join joins a table with itself. Polars names the clashing column of the right side category_right; pass suffix="_b" for a shorter name.

Hint 2

category < category_b keeps each unordered pair once and drops pairs of a category with itself.

Hint 3

sort takes several columns and a list for descending=[...], one flag per column.

Solution
order_cats = sales.select("order_id", "category").unique()
pairs = (
order_cats.join(order_cats, on="order_id", suffix="_b")
.filter(pl.col("category") < pl.col("category_b"))
.group_by("category", "category_b")
.agg(orders=pl.len())
.sort("orders", "category", "category_b", descending=[True, False, False])
.head(5)
)
print(pairs)
multi = order_cats.group_by("order_id").agg(n=pl.len()).filter(pl.col("n") > 1).height
print("orders with 2+ categories:", multi)
assert pairs["orders"].is_sorted(descending=True)
assert (pairs["category"] < pairs["category_b"]).all()
Output
shape: (5, 3)
┌─────────────┬─────────────┬────────┐
│ category ┆ category_b ┆ orders │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ u32 │
╞═════════════╪═════════════╪════════╡
│ Clothing ┆ Electronics ┆ 488 │
│ Clothing ┆ Sports ┆ 441 │
│ Electronics ┆ Sports ┆ 407 │
│ Beauty ┆ Clothing ┆ 404 │
│ Clothing ┆ Home ┆ 392 │
└─────────────┴─────────────┴────────┘
orders with 2+ categories: 3675

How it works:

  1. unique() keeps one row per order and category, so an order with two clothing items counts once for Clothing.
  2. The self join pairs every category of an order with every other category of the same order.
  3. The string comparison < keeps one of the two mirror pairs (Beauty–Clothing, not Clothing–Beauty) and removes self pairs.
  4. Clothing appears in four of the five top pairs. It is the category with the most lines (see the data dictionary), so it lands in many baskets. A fair comparison divides the pair’s share of orders by the product of each category’s share of orders. That ratio is the lift (module 25): above 1 means the two are bought together more often than chance predicts.

Alternative: collect each order’s categories into a sorted list, then count the lists. This shows whole baskets instead of pairs.

baskets = (
order_cats.group_by("order_id")
.agg(pl.col("category").sort().alias("basket"))
.filter(pl.col("basket").list.len() == 2)
.with_columns(pl.col("basket").list.join(" + "))
.group_by("basket")
.agg(orders=pl.len())
.sort("orders", "basket", descending=[True, False])
.head(3)
)
print(baskets.rows())
Output
[('Clothing + Electronics', 270), ('Clothing + Sports', 237), ('Electronics + Sports', 232)]

M31-X04 · A data-quality gate for new extracts

Section titled “M31-X04 · A data-quality gate for new extracts”
Challenge

Each week a Parquet extract like data/sales_sample.parquet arrives. Write a function check_sales(df: pl.DataFrame) -> list[str] that returns a list of problems (an empty list means the extract passes). It checks: order_date is a Date; no nulls; the key (order_id, product_id) is unique; region only holds the four known regions; revenue matches the formula within 0.01. Run it on the sample after converting order_date to Date, then on a copy with three planted problems.

Expected output
["order_date is Datetime(time_unit='us', time_zone=None), not Date"]
[]
- duplicate key in 2 of 501 rows
- unknown region in 1 of 501 rows
- revenue formula broken in 1 of 501 rows
Starter
REGIONS = ["North", "South", "East", "West"]
def check_sales(df: pl.DataFrame) -> list[str]:
problems: list[str] = []
# TODO: one if-block per rule; append a short message when it fails
return problems
sample = pl.read_parquet("data/sales_sample.parquet")
# TODO: cast order_date to pl.Date, run the check, print the result
# TODO: plant problems in a copy, run the check again
Hint 1

df.null_count().sum_horizontal().item() is the total null count. df.select("order_id", "product_id").is_duplicated().sum() counts duplicated keys.

Hint 2

~pl.col("region").is_in(REGIONS) marks unknown regions. Count them with df.filter(...).height.

Hint 3

Plant problems with with_columns: replace one region with pl.when(pl.col("order_id") == "O000002").then(pl.lit("Nort")).otherwise(pl.col("region")), and append a duplicate row with pl.concat.

Solution
REGIONS = ["North", "South", "East", "West"]
def check_sales(df: pl.DataFrame) -> list[str]:
problems: list[str] = []
if df.schema["order_date"] != pl.Date:
problems.append(f"order_date is {df.schema['order_date']}, not Date")
nulls = df.null_count().sum_horizontal().item()
if nulls:
problems.append(f"null cells: {nulls}")
dups = df.select("order_id", "product_id").is_duplicated().sum()
if dups:
problems.append(f"duplicate key in {dups} of {df.height} rows")
bad_region = df.filter(~pl.col("region").is_in(REGIONS)).height
if bad_region:
problems.append(f"unknown region in {bad_region} of {df.height} rows")
formula = pl.col("unit_price") * pl.col("quantity") * (1 - pl.col("discount"))
off = df.filter((formula.round(2) - pl.col("revenue")).abs() > 0.01).height
if off:
problems.append(f"revenue formula broken in {off} of {df.height} rows")
return problems
sample = pl.read_parquet("data/sales_sample.parquet")
print(check_sales(sample))
clean = sample.with_columns(pl.col("order_date").cast(pl.Date))
print(check_sales(clean))
broken = pl.concat([clean, clean.head(1)]).with_columns(
region=pl.when(pl.col("order_id") == "O000002")
.then(pl.lit("Nort"))
.otherwise(pl.col("region")),
revenue=pl.when(pl.col("order_id") == "O000003")
.then(pl.col("revenue") * 10)
.otherwise(pl.col("revenue")),
)
for problem in check_sales(broken):
print("-", problem)
assert check_sales(clean) == []
assert len(check_sales(broken)) == 3
Output
["order_date is Datetime(time_unit='us', time_zone=None), not Date"]
[]
- duplicate key in 2 of 501 rows
- unknown region in 1 of 501 rows
- revenue formula broken in 1 of 501 rows

How it works:

  1. Each rule is one Polars expression and one if. The function collects messages instead of raising at the first problem, so one run reports everything.
  2. The raw Parquet sample fails only the dtype rule: Parquet stores order_date as a timestamp. Casting to Date fixes it.
  3. The broken copy has 501 rows: a duplicated first row, one misspelled region and one revenue ten times too high.
  4. is_duplicated() marks both copies of a duplicate, which is why the message says 2 rows.

Alternative: let the dtype system enforce the region rule. Casting to an Enum raises an error for any value outside the list, so a misspelled region cannot get past the load step.

broken.with_columns(pl.col("region").cast(pl.Enum(REGIONS)))
Output
polars.exceptions.InvalidOperationError: conversion from `str` to `enum` failed in column 'region' for 1 out of 500 values: ["Nort"]
Challenge

Promotion days show up as daily revenue far above normal. Compute the daily revenue, a baseline equal to the mean of the previous 28 days (the day itself excluded), and the ratio of each day to its baseline (2 decimals). Print the 5 days with the highest ratio, with the weekday name. Days without a full 28-day history have no baseline and must not appear.

Expected output
shape: (5, 5)
┌────────────┬─────┬──────────┬──────────┬───────┐
│ order_date ┆ day ┆ revenue ┆ baseline ┆ ratio │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ date ┆ str ┆ f64 ┆ f64 ┆ f64 │
╞════════════╪═════╪══════════╪══════════╪═══════╡
│ 2023-11-24 ┆ Fri ┆ 31222.69 ┆ 4925.44 ┆ 6.34 │
│ 2024-11-29 ┆ Fri ┆ 33619.18 ┆ 7757.7 ┆ 4.33 │
│ 2024-05-11 ┆ Sat ┆ 12646.06 ┆ 3672.63 ┆ 3.44 │
│ 2024-11-02 ┆ Sat ┆ 16896.3 ┆ 5584.94 ┆ 3.03 │
│ 2023-08-11 ┆ Fri ┆ 12783.95 ┆ 4518.41 ┆ 2.83 │
└────────────┴─────┴──────────┴──────────┴───────┘
Starter
daily = (
sales.group_by("order_date")
# TODO: daily revenue, sorted by date
)
# TODO: baseline = rolling 28-day mean, shifted by one day
# TODO: ratio = revenue / baseline; drop null baselines; top 5 by ratio
# TODO: add the weekday name with .dt.strftime("%a")
Hint 1

pl.col("revenue").rolling_mean(28) is the mean of the current day and the 27 days before it. .shift(1) moves each value down one row, so day d gets the mean of days d−28 to d−1.

Hint 2

The first 28 rows have a null baseline. drop_nulls("baseline") removes them.

Solution
daily = (
sales.group_by("order_date")
.agg(pl.col("revenue").sum().round(2))
.sort("order_date")
)
spikes = (
daily.with_columns(baseline=pl.col("revenue").rolling_mean(28).shift(1))
.drop_nulls("baseline")
.with_columns(
ratio=(pl.col("revenue") / pl.col("baseline")).round(2),
baseline=pl.col("baseline").round(2),
day=pl.col("order_date").dt.strftime("%a"),
)
.sort("ratio", descending=True)
.head(5)
.select("order_date", "day", "revenue", "baseline", "ratio")
)
print(spikes)
assert daily.height == 731
assert spikes["ratio"].min() > 2.5
Output
shape: (5, 5)
┌────────────┬─────┬──────────┬──────────┬───────┐
│ order_date ┆ day ┆ revenue ┆ baseline ┆ ratio │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ date ┆ str ┆ f64 ┆ f64 ┆ f64 │
╞════════════╪═════╪══════════╪══════════╪═══════╡
│ 2023-11-24 ┆ Fri ┆ 31222.69 ┆ 4925.44 ┆ 6.34 │
│ 2024-11-29 ┆ Fri ┆ 33619.18 ┆ 7757.7 ┆ 4.33 │
│ 2024-05-11 ┆ Sat ┆ 12646.06 ┆ 3672.63 ┆ 3.44 │
│ 2024-11-02 ┆ Sat ┆ 16896.3 ┆ 5584.94 ┆ 3.03 │
│ 2023-08-11 ┆ Fri ┆ 12783.95 ┆ 4518.41 ┆ 2.83 │
└────────────┴─────┴──────────┴──────────┴───────┘

How it works:

  1. Daily revenue must be sorted by date before any rolling window.
  2. rolling_mean(28).shift(1) gives a trailing baseline that does not include the day itself, so a spike cannot raise its own baseline.
  3. Black Friday 2023 (2023-11-24) is more than 6 times its baseline. Black Friday 2024 (2024-11-29) has a higher revenue but a lower ratio, because its baseline is higher: 7757.7 against 4925.44.
  4. Interpretation: a ratio flags unusual days relative to their recent past. The other three days (in May, early November and August) are not on the promotion list of the data dictionary. A flag is a reason to look at a day’s orders, not proof of a promotion.

Alternative: use the median instead of the mean for the baseline. A robust baseline is less pulled up by earlier spikes inside the window.

robust = (
daily.with_columns(baseline=pl.col("revenue").rolling_median(28).shift(1))
.drop_nulls("baseline")
.with_columns(ratio=(pl.col("revenue") / pl.col("baseline")).round(2))
.sort("ratio", descending=True)
.head(3)
)
for day, ratio in robust.select("order_date", "ratio").iter_rows():
print(day.isoformat(), ratio)
Output
2023-11-24 7.36
2024-11-29 4.31
2024-05-11 3.9

M31-X06 · Port a store report and prove it matches

Section titled “M31-X06 · Port a store report and prove it matches”
Challenge

Refactor procedural pandas code into a reusable, tested Polars function. Write store_report(sales_lf: pl.LazyFrame, stores_lf: pl.LazyFrame, year: int) -> pl.LazyFrame that returns, per store and for one year, the city, revenue (2 decimals), orders and the online share of revenue (3 decimals), sorted by revenue descending. Then compute the same table with pandas and prove equality with assert_frame_equal. Print the first 3 rows of the 2024 report.

pandas version
import pandas as pd
df = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
df = df[df["order_date"].dt.year == 2024]
df["online_revenue"] = df["revenue"].where(df["channel"] == "online", 0.0)
report = df.groupby("store_id", as_index=False).agg(
revenue=("revenue", "sum"),
orders=("order_id", "nunique"),
online_revenue=("online_revenue", "sum"),
)
report["online_share"] = (report["online_revenue"] / report["revenue"]).round(3)
report["revenue"] = report["revenue"].round(2)
report = report.merge(
pd.read_csv("data/stores.csv")[["store_id", "city"]], on="store_id"
)
report = report.sort_values("revenue", ascending=False, ignore_index=True)
print(report[["store_id", "city", "revenue", "orders", "online_share"]].head(3))
Expected output
shape: (3, 5)
┌──────────┬──────────┬───────────┬────────┬──────────────┐
│ store_id ┆ city ┆ revenue ┆ orders ┆ online_share │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 ┆ i64 ┆ f64 │
╞══════════╪══════════╪═══════════╪════════╪══════════════╡
│ S07 ┆ New York ┆ 263924 ┆ 1058 ┆ 0.433 │
│ S01 ┆ Chicago ┆ 220899.08 ┆ 897 ┆ 0.434 │
│ S10 ┆ Seattle ┆ 213238.5 ┆ 834 ┆ 0.439 │
└──────────┴──────────┴───────────┴────────┴──────────────┘
matches pandas: 12 stores
Starter
from polars.testing import assert_frame_equal
def store_report(
sales_lf: pl.LazyFrame, stores_lf: pl.LazyFrame, year: int
) -> pl.LazyFrame:
# TODO: filter the year, group by store_id, three aggregations,
# TODO: online_share, join the city, select and sort
...
# TODO: report = store_report(pl.scan_csv(...), pl.scan_csv(...), 2024).collect()
# TODO: run the pandas version, convert it, compare with assert_frame_equal
Hint 1

The online revenue of a group is pl.col("revenue").filter(pl.col("channel") == "online").sum().

Hint 2

pandas nunique returns int64; Polars n_unique returns UInt32. Cast orders to pl.Int64 in your function, or pass check_dtypes=False.

Hint 3

Sort by revenue and then by store_id, so that ties (if any) cannot change the order.

Solution
import pandas as pd
from polars.testing import assert_frame_equal
def store_report(
sales_lf: pl.LazyFrame, stores_lf: pl.LazyFrame, year: int
) -> pl.LazyFrame:
online = pl.col("channel") == "online"
return (
sales_lf.filter(pl.col("order_date").dt.year() == year)
.group_by("store_id")
.agg(
revenue=pl.col("revenue").sum(),
orders=pl.col("order_id").n_unique().cast(pl.Int64),
online_revenue=pl.col("revenue").filter(online).sum(),
)
.with_columns(
online_share=(pl.col("online_revenue") / pl.col("revenue")).round(3),
revenue=pl.col("revenue").round(2),
)
.join(stores_lf.select("store_id", "city"), on="store_id", validate="1:1")
.select("store_id", "city", "revenue", "orders", "online_share")
.sort(["revenue", "store_id"], descending=[True, False])
)
report = store_report(
pl.scan_csv("data/sales.csv", try_parse_dates=True),
pl.scan_csv("data/stores.csv"),
2024,
).collect()
print(report.head(3))
df = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
df = df[df["order_date"].dt.year == 2024]
df["online_revenue"] = df["revenue"].where(df["channel"] == "online", 0.0)
expected = df.groupby("store_id", as_index=False).agg(
revenue=("revenue", "sum"),
orders=("order_id", "nunique"),
online_revenue=("online_revenue", "sum"),
)
expected["online_share"] = (expected["online_revenue"] / expected["revenue"]).round(3)
expected["revenue"] = expected["revenue"].round(2)
expected = expected.merge(
pd.read_csv("data/stores.csv")[["store_id", "city"]], on="store_id"
)
expected = expected.sort_values("revenue", ascending=False, ignore_index=True)
expected = expected[["store_id", "city", "revenue", "orders", "online_share"]]
assert_frame_equal(report, pl.from_pandas(expected))
print("matches pandas:", report.height, "stores")
assert report["revenue"].is_sorted(descending=True)
Output
shape: (3, 5)
┌──────────┬──────────┬───────────┬────────┬──────────────┐
│ store_id ┆ city ┆ revenue ┆ orders ┆ online_share │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 ┆ i64 ┆ f64 │
╞══════════╪══════════╪═══════════╪════════╪══════════════╡
│ S07 ┆ New York ┆ 263924 ┆ 1058 ┆ 0.433 │
│ S01 ┆ Chicago ┆ 220899.08 ┆ 897 ┆ 0.434 │
│ S10 ┆ Seattle ┆ 213238.5 ┆ 834 ┆ 0.439 │
└──────────┴──────────┴───────────┴────────┴──────────────┘
matches pandas: 12 stores

How it works:

  1. The function takes and returns LazyFrames, so a caller can add steps (a filter, a join) and the optimizer still sees the whole plan.
  2. filter(online) inside agg replaces the helper column of the pandas version.
  3. The cast to Int64 matches the pandas dtype, so assert_frame_equal can check dtypes as well as values.
  4. The pandas code mutates df step by step. The Polars function is one expression chain with no hidden state, which makes it easy to test with other years or other data.

Alternative: test the function on a tiny hand-made table, where you can check the answer by eye. This is the pattern of module 14: small inputs, exact expected outputs.

from datetime import date
tiny_sales = pl.LazyFrame(
{
"order_id": ["O1", "O1", "O2"],
"order_date": [date(2024, 1, 5)] * 3,
"store_id": ["S01", "S01", "S02"],
"channel": ["online", "online", "store"],
"revenue": [10.0, 30.0, 60.0],
}
)
tiny_stores = pl.LazyFrame(
{"store_id": ["S01", "S02"], "city": ["Chicago", "Minneapolis"]}
)
print(store_report(tiny_sales, tiny_stores, 2024).collect().rows())
Output
[('S02', 'Minneapolis', 60.0, 1, 0.0), ('S01', 'Chicago', 40.0, 1, 1.0)]