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:
- Read the task and the expected output.
- Copy the setup block and then the starter code into a script (for example
exercise.py). Replace each to-do comment with your code. - Run the script with
python exercise.py. Compare your output with the expected output. - 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
Section titled “Warm-up”M31-W01 · Build a table of store targets
Section titled “M31-W01 · Build a table of store targets”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.
shape: (3, 2)┌──────────┬────────┐│ store_id ┆ target ││ --- ┆ --- ││ str ┆ i64 │╞══════════╪════════╡│ S01 ┆ 400000 ││ S04 ┆ 380000 ││ S07 ┆ 450000 │└──────────┴────────┘3 Int64# 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.Int64shape: (3, 2)┌──────────┬────────┐│ store_id ┆ target ││ --- ┆ --- ││ str ┆ i64 │╞══════════╪════════╡│ S01 ┆ 400000 ││ S04 ┆ 380000 ││ S07 ┆ 450000 │└──────────┴────────┘3 Int64How it works:
- Each dict key becomes a column name and each list becomes a column.
- Polars infers
Stringfor the ids andInt64for the whole numbers. The underscores in400_000only help you read the literal. heightcounts rows;schemamaps 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)(3, 2) ['store_id', 'target']M31-W02 · Fix the date column
Section titled “M31-W02 · Fix the date column”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.
Dateshape: (3, 3)┌──────────┬──────────────┬──────┐│ store_id ┆ city ┆ year ││ --- ┆ --- ┆ --- ││ str ┆ str ┆ i32 │╞══════════╪══════════════╪══════╡│ S12 ┆ Denver ┆ 2023 ││ S06 ┆ Miami ┆ 2018 ││ S09 ┆ Philadelphia ┆ 2017 │└──────────┴──────────────┴──────┘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 newestHint 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.Dateassert newest["store_id"].to_list() == ["S12", "S06", "S09"]Dateshape: (3, 3)┌──────────┬──────────────┬──────┐│ store_id ┆ city ┆ year ││ --- ┆ --- ┆ --- ││ str ┆ str ┆ i32 │╞══════════╪══════════════╪══════╡│ S12 ┆ Denver ┆ 2023 ││ S06 ┆ Miami ┆ 2018 ││ S09 ┆ Philadelphia ┆ 2017 │└──────────┴──────────────┴──────┘How it works:
- Without
try_parse_dates=True,openedisString, and.dt.year()on text raises anInvalidOperationError. - With the option, Polars recognizes the
YYYY-MM-DDpattern and stores real dates. - Sorting a
Datecolumn sorts by time. Sorting the text would also work for ISO dates, but.dtwould 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())Date 2023-06-15M31-W03 · Select and rename columns
Section titled “M31-W03 · Select and rename columns”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.
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 │└──────────┴────────────────────────┴───────────┘# TODO: select order_id, product and revenue_k from sales# TODO: print the first 3 rowsHint 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.066shape: (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:
"order_id"and"product"are short forpl.col("order_id")andpl.col("product").- The keyword argument names the new column. The parentheses make the division run before
round. selectreturns 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)['order_id', 'product', 'revenue_k']M31-W04 · Count deep online discounts
Section titled “M31-W04 · Count deep online discounts”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.
646 94994.03# TODO: keep the online lines with discount 0.2# TODO: print the number of lines and their total revenueHint 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.height646 94994.03How it works:
- The two predicates are combined with “and”.
- Comparing a float with
== 0.2is safe here: the file stores the exact literal0.2, so Polars reads the same float. deep["revenue"]is a Series, andsum()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))(646, 94994.03)M31-W05 · Predict select versus with_columns
Section titled “M31-W05 · Predict select versus with_columns”Predict the output: read the code and write down the three printed lines before you run it.
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 hereAcceptance 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]['units'] ['store_id', 'units'] ['store_id', 'units', 'double'][3, 5] [6, 10] [3, 5]1How it works:
selectreturns only the expression’s result.pl.col("units") * 2is still namedunits.breplacesunitswith the doubled values, because the new column has the same name.cadds a new columndoubleand keepsunitsas it was.- No context changes
df. Every call returns a new DataFrame, sodf["units"]is still[3, 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”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.
shape: (3, 2)┌─────────┬──────────┐│ band ┆ products ││ --- ┆ --- ││ str ┆ u32 │╞═════════╪══════════╡│ budget ┆ 9 ││ mid ┆ 12 ││ premium ┆ 9 │└─────────┴──────────┘# TODO: add band with pl.when(...).then(...).when(...).then(...).otherwise(...)# TODO: count products per band and sort by bandHint 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() == 30assert counts["band"].to_list() == ["budget", "mid", "premium"]shape: (3, 2)┌─────────┬──────────┐│ band ┆ products ││ --- ┆ --- ││ str ┆ u32 │╞═════════╪══════════╡│ budget ┆ 9 ││ mid ┆ 12 ││ premium ┆ 9 │└─────────┴──────────┘How it works:
- The chain checks the conditions in order, like
if/elif/else. A price of 29.99 is caught by the first branch. - A price of 150 or more fails both tests and gets
premiumfromotherwise. group_byplussort("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"))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”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.
['BEA', 'BOO', 'CLO', 'ELE', 'HOM', 'SPO']["Chef's Knife Set", 'Cotton Bed Sheet Set', 'Shampoo and Conditioner Set']# 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 namesHint 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() == 6assert len(sets) == 3['BEA', 'BOO', 'CLO', 'ELE', 'HOM', 'SPO']["Chef's Knife Set", 'Cotton Bed Sheet Set', 'Shampoo and Conditioner Set']How it works:
.str.slice(0, 3)and.str.to_uppercase()run on every row of the column at once.unique()returns the six distinct codes in no fixed order;sorted()fixes it..str.containstakes a regular expression.Sethas 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)['BEA', 'BOO', 'CLO', 'ELE', 'HOM', 'SPO']3M31-W08 · Fix the channel labels
Section titled “M31-W08 · Fix the channel labels”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.
shape: (2, 2)┌───────┬───────┐│ label ┆ lines ││ --- ┆ --- ││ str ┆ u32 │╞═══════╪═══════╡│ shop ┆ 11733 ││ web ┆ 8495 │└───────┴───────┘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 bugsHint 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.heightassert counts["label"].to_list() == ["shop", "web"]shape: (2, 2)┌───────┬───────┐│ label ┆ lines ││ --- ┆ --- ││ str ┆ u32 │╞═══════╪═══════╡│ shop ┆ 11733 ││ web ┆ 8495 │└───────┴───────┘How it works:
then("web")made Polars look for a column calledweband raiseColumnNotFoundError.pl.lit("web")is the constant text.group_bycomputes groups in parallel, so the order ofshopandwebcan change between runs.sort("label")fixes it.- 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())[('shop', 11733), ('web', 8495)]M31-C01 · Category growth from 2023 to 2024
Section titled “M31-C01 · Category growth from 2023 to 2024”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.
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 │└─────────────┴────────┴────────┴────────────┘# 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, descendingHint 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 == 6shape: (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:
- The keyword key
year=names the computed group column. - Sorting by category and year before the pivot fixes the column order:
2023comes before2024. - The pivot turns the integer years into column names, which are always strings.
- 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())['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”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.
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 │└─────────┴──────┴────────┴────────┘# TODO: group by channel and year# TODO: aggregate revenue (sum) and orders (distinct order_id)# TODO: add aov = revenue / orders, rounded to 2 decimals; sortHint 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 == 4assert aov["orders"].sum() == sales["order_id"].n_unique()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:
n_unique()counts each order once, even when it has three lines.- The AOV is computed from the totals after the aggregation.
- 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)('online', 2023, 249.74, 108.41)('online', 2024, 237.45, 119.47)('store', 2023, 241.95, 116.96)('store', 2024, 240.71, 119.98)M31-C03 · Revenue per square meter
Section titled “M31-C03 · Revenue per square meter”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.
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 │└──────────┴───────────────┴──────────┴─────────┘# 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 shownHint 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 == 5assert ranked["per_sqm"].is_sorted(descending=True)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:
- The aggregation shrinks 20,228 lines to 12 rows before the join, so the join is tiny.
validate="1:1"proves that each store appears once on both sides.- 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())['S10', 'S03', 'S01', 'S11', 'S09']M31-C04 · Stores with no Christmas orders
Section titled “M31-C04 · Stores with no Christmas orders”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.
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 │└──────────┴───────────────┘# 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 citiesHint 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.height6 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:
- The filter keeps the 6 lines of Christmas Day 2023; all of them are online.
- The anti join keeps every store whose id does not appear among those lines.
- 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())['S01', 'S02', 'S04', 'S05', 'S06', 'S08', 'S11', 'S12']M31-C05 · Category share inside each region
Section titled “M31-C05 · Category share inside each region”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.
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 │└─────────────┴────────┴───────────┘# TODO: revenue per region and category# TODO: share_pct = revenue / region total * 100, with .over("region")# TODO: keep Books and Electronics; sort by category, regionHint 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 == 8assert shares.filter(pl.col("category") == "Electronics")["share_pct"].min() > 45shape: (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:
- After the
group_by, each row is one region and category. sum().over("region")adds the six category totals of each region and writes the result to each of its rows.- 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())[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?”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.
first sale: 2023-06-15passed 50k: 2023-11-23 50085.21# TODO: daily revenue of S12, sorted by date# TODO: running total with cum_sum# TODO: first row where the running total >= 50_000Hint 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_000first sale: 2023-06-15passed 50k: 2023-11-23 50085.21How it works:
- The daily
group_byis sorted by date, socum_sumadds the days in time order. - The filter keeps every day at or above 50,000; the first of them is the answer.
- Indexing a Series with
[0]returns a Pythondateorfloat.
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])2023-11-23M31-C07 · Inspect a lazy query plan
Section titled “M31-C07 · Inspect a lazy query plan”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.
PROJECT 2/13 COLUMNSPROJECT 2/6 COLUMNSSELECTION: col("launch_date") >= 2022-01-01shape: (8, 2)┌────────────┬───────┐│ product_id ┆ units ││ --- ┆ --- ││ str ┆ i64 │╞════════════╪═══════╡│ P004 ┆ 599 ││ P005 ┆ 842 ││ P007 ┆ 457 ││ P019 ┆ 954 ││ P020 ┆ 579 ││ P023 ┆ 697 ││ P025 ┆ 411 ││ P029 ┆ 749 │└────────────┴───────┘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 == 8assert result["units"].min() > 0PROJECT 2/13 COLUMNSPROJECT 2/6 COLUMNSSELECTION: col("launch_date") >= 2022-01-01shape: (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:
- The sales scan reads only
product_idandquantity: 2 of 13 columns. - The products scan reads
product_idandlaunch_date, and the date filter runs inside it. Only 8 product rows reach the join. - 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())8 5288M31-C08 · Port a pandas summary to Polars
Section titled “M31-C08 · Port a pandas summary to Polars”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.
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())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 │└────────┴──────────────┴─────────────────────┘# 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 discountHint 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()))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:
- 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_bywith two expressions. is_onlineis an expression stored in a variable, used twice.filterinsideaggworks per group: it keeps only the online lines of each region before the mean.from_pandasturns the pandas result into Polars, andequalscompares 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())[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”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.
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) + gpshape: (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 │└─────────────┴──────────────┘# 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 resultHint 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) + gpfor category, value in fast.iter_rows(): assert math.isclose(profit[category], value, abs_tol=0.01)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:
- The join replaces the dict lookup;
validate="m:1"guarantees one cost per product. - The filter replaces the
if; the expression inaggreplaces the loop body and the running sum. - 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.iscloseand 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())['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”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).
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 │└─────────┴───────┴────────┴────────────┘# 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 monthHint 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.heightshape: (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:
is_betweenincludes both end dates by default.on_columnslists the new columns and their order, so the result does not depend on which channel appears first.- The row order still comes from the unsorted
group_by, so the finalsort("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())[('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?”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).
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.# TODO: add weekend = weekday() >= 6# TODO: online share and line count per weekend flag, sorted# TODO: difference in percentage points; print the sentenceHint 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) < 2shape: (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:
- The group key is a Boolean expression named
weekend; sorting putsfalsebeforetrue. - Both groups have about 42% online lines. The difference is a fraction of a point and slightly negative.
- Interpretation: the channel mix does not depend on the day type. Weekend days have more lines per day (the
per_daycolumn), 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())[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”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.
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: 29bulk = 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 uniqueHint 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)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: 29How it works:
- Both versions give the same 10 stores.
- The inner join first builds one row per bulk line (29 rows with 17 columns), then
uniquethrows most of them away. - 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.
Challenge
Section titled “Challenge”M31-X01 · The runner-up category of each month
Section titled “M31-X01 · The runner-up category of each month”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.
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]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; collectHint 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 == 12assert runner_up["month"].to_list() == list(range(1, 13))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:
- The pipeline is one lazy chain. The optimizer reads only the columns it needs and pushes the year filter into the sales scan.
- The
filterwith a window keeps the rank-2 category of each month without a separate ranking column. - The margin is computed after both sums, then the gross profit is rounded. The order matters: rounding first would change the margin slightly.
pl.Config(tbl_rows=12)shows all 12 rows for this one print.- 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()[6, 7, 8]M31-X02 · Repeat customers and first-purchase cohorts
Section titled “M31-X02 · Repeat customers and first-purchase cohorts”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).
3254 0.468 4.57shape: (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 │└─────────┴───────────────┴───────────────┴───────────┘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 2023Hint 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 == 3254assert ( cohorts["new_customers"].sum() == customers.filter(pl.col("first").dt.year() == 2023).height)3254 0.468 4.57shape: (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:
- One
group_bycollapses 20,228 lines to 3,254 customers with three facts each. customers["years"] == 2is a Boolean Series; its mean is the share of customers who bought in both years.- 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. - Interpretation: every 2023 cohort holds many customers who signed up before 2023 (the
older_pctcolumn), 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())3254M31-X03 · Which categories are bought together?
Section titled “M31-X03 · Which categories are bought together?”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.
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: 3675order_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 5Hint 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).heightprint("orders with 2+ categories:", multi)assert pairs["orders"].is_sorted(descending=True)assert (pairs["category"] < pairs["category_b"]).all()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: 3675How it works:
unique()keeps one row per order and category, so an order with two clothing items counts once for Clothing.- The self join pairs every category of an order with every other category of the same order.
- The string comparison
<keeps one of the two mirror pairs (Beauty–Clothing, not Clothing–Beauty) and removes self pairs. - 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())[('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”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.
["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 rowsREGIONS = ["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 againHint 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["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 rowsHow it works:
- 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. - The raw Parquet sample fails only the dtype rule: Parquet stores
order_dateas a timestamp. Casting toDatefixes it. - The broken copy has 501 rows: a duplicated first row, one misspelled region and one revenue ten times too high.
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)))polars.exceptions.InvalidOperationError: conversion from `str` to `enum` failed in column 'region' for 1 out of 500 values: ["Nort"]M31-X05 · Detect promotion days
Section titled “M31-X05 · Detect promotion days”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.
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 │└────────────┴─────┴──────────┴──────────┴───────┘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 == 731assert spikes["ratio"].min() > 2.5shape: (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:
- Daily revenue must be sorted by date before any rolling window.
rolling_mean(28).shift(1)gives a trailing baseline that does not include the day itself, so a spike cannot raise its own baseline.- 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.
- 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)2023-11-24 7.362024-11-29 4.312024-05-11 3.9M31-X06 · Port a store report and prove it matches
Section titled “M31-X06 · Port a store report and prove it matches”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.
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))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 storesfrom 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_equalHint 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 pdfrom 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)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 storesHow it works:
- The function takes and returns LazyFrames, so a caller can add steps (a filter, a join) and the optimizer still sees the whole plan.
filter(online)insideaggreplaces the helper column of the pandas version.- The cast to
Int64matches the pandas dtype, soassert_frame_equalcan check dtypes as well as values. - The pandas code mutates
dfstep 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())[('S02', 'Minneapolis', 60.0, 1, 0.0), ('S01', 'Chicago', 40.0, 1, 1.0)]