Skip to content

Part 4 checkpoint

This checkpoint tests Part 4 as a whole. Each exercise is a small piece of real analyst work on the course datasets: you load and clean the data, compute the numbers, draw the chart, check the result with a statistical test and write the conclusion. Most exercises mix two to four modules, for example SQL for the query, pandas or Polars for the reshaping and SciPy for the test. The tasks combine the skills in new ways; some reuse a dataset from a module, but none repeats a module exercise or mini-project.

How to use it:

  1. Work without your notes first. Read the task and the expected output, then write your code.
  2. Stuck for more than 10 minutes? Open one hint at a time.
  3. Open the solution only after a real attempt. Compare your code, your chart and your written conclusion with it, not only your printed numbers.
  4. Score yourself with the rubric at the end of the page.

Plan about 9 to 12 hours in total: 15–20 minutes for each of the 3 warm-ups, 30–45 minutes for each of the 10 core exercises and 60–75 minutes for each of the 3 challenges. You can split the work over several sessions.

Exercise Tier Type Modules
P4-01 Warm-up Predict the output 23, 24, 26, 29
P4-02 Warm-up Fix the bugs 24, 25, 27
P4-03 Warm-up Write the code 25, 30
P4-04 Core Fix the bugs 24, 25, 26
P4-05 Core Write the code 24, 25, 30
P4-06 Core Write the code 28, 29, 31
P4-07 Core Interpret a result 25, 27, 28, 29
P4-08 Core Refactor 23, 25, 30, 31
P4-09 Core Write the code 25, 26, 28
P4-10 Core Choose and justify 23, 27, 28, 29
P4-11 Core Interpret a result 27, 28, 29, 30
P4-12 Core Interpret a result 27, 28, 29
P4-13 Core Write the code 24, 25, 28
P4-14 Challenge Fix the method 23, 27, 28, 31
P4-15 Challenge Interpret a result 23, 27, 28, 29
P4-16 Challenge Choose and justify 28, 29, 30

Work in your course project folder with Python 3.12 or newer and the virtual environment of the course. The data/ folder from Get the data must be in that folder, because every path on this page is relative to it (data/sales.csv). The data dictionary lists the facts you can check your results against. Run each exercise as its own script, for example python p4_05.py. A chart window opens at each plt.show(); close it to continue. Scripts that write files write to output/, never into data/.

Every exercise starts from this block. It imports the libraries of Part 4, fixes how pandas and Polars print tables and sets one color-blind-friendly chart theme.

import sqlite3
import duckdb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import polars as pl
import seaborn as sns
import statsmodels.formula.api as smf
from scipy import stats
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
pl.Config.set_tbl_width_chars(100)
plt.rcdefaults()
sns.set_theme(style="whitegrid", palette="colorblind")

Each solution ends with assert checks. Add the same checks to your own code: a silent run means that every check passed. A chart cannot be compared character by character, so the solutions also print the numbers behind each chart.

P4-01 · Predict the output: gaps, views and small integers

Section titled “P4-01 · Predict the output: gaps, views and small integers”
Warm-up

Predict the output: a sensor sends four temperatures with one gap, a store system stores unit counts as int8, and an export sends quantities as text with - for “unknown”. Write down what each print() shows, then run the code.

Acceptance criteria:

  • Write your prediction for all 7 lines before you run the code.
  • Your prediction matches the Output in the solution, line by line.
  • For each line you got wrong, you can name the rule and the module that explains it.
Starter
temps = np.array([21.5, np.nan, 23.0, 22.5])
print(temps.mean(), np.nanmean(temps))
window = temps[1:3]
window[0] = 20.0
print(temps)
hot = temps[temps > 22]
hot[0] = 0.0
print(temps.max())
units = np.array([120, 100], dtype=np.int8)
print(units + 10, units.sum())
s = pd.Series([2.0, 4.0, 4.0, 6.0])
print(round(s.std(), 3), round(np.std(s.to_numpy()), 3))
qty = pd.Series(["2", "-", "3"])
print(pd.to_numeric(qty, errors="coerce").sum())
print(np.nan == np.nan, pd.isna(np.nan))
# TODO: write your prediction for each print() line before you run it
Hint 1

A basic slice such as temps[1:3] is a view of the same memory. A boolean mask such as temps[temps > 22] makes a copy.

Hint 2

Which range of integers does int8 hold?

Solution
temps = np.array([21.5, np.nan, 23.0, 22.5])
print(temps.mean(), np.nanmean(temps))
window = temps[1:3]
window[0] = 20.0
print(temps)
hot = temps[temps > 22]
hot[0] = 0.0
print(temps.max())
units = np.array([120, 100], dtype=np.int8)
print(units + 10, units.sum())
s = pd.Series([2.0, 4.0, 4.0, 6.0])
print(round(s.std(), 3), round(np.std(s.to_numpy()), 3))
qty = pd.Series(["2", "-", "3"])
print(pd.to_numeric(qty, errors="coerce").sum())
print(np.nan == np.nan, pd.isna(np.nan))
assert np.shares_memory(temps, window)
assert not np.shares_memory(temps, hot)
assert units.dtype == np.int8 and units.sum() == 220
Output
nan 22.333333333333332
[21.5 20. 23. 22.5]
23.0
[-126 110] 220
1.633 1.414
5.0
False True

How it works:

  1. mean() propagates NaN, so the first value is nan. nanmean() skips the gap and averages the other three values (module 23).
  2. temps[1:3] is a view. Writing 20.0 into window[0] writes into temps[1], so the gap disappears from temps too. This is how a “harmless” fix in a helper changes the caller’s data.
  3. temps[temps > 22] is a copy. Setting hot[0] to 0 does not change temps. The NaN is gone (step 2), so max() returns 23.0 and not nan.
  4. 120 + 10 is 130, which does not fit in int8: it wraps to 130 − 256 = −126. sum() adds in a 64-bit integer, so it gives 220. Choose the dtype for the largest value you expect (module 23).
  5. pandas uses ddof=1 (the sample standard deviation) and NumPy uses ddof=0. On 4 values the difference is large: 1.633 against 1.414 (module 29).
  6. errors="coerce" turns - into NaN, and sum() skips NaN: 2 + 3 = 5.0. Count the new gaps after each coercion, or you lose rows without noticing (module 26).
  7. NaN never equals anything, not even NaN. Test for gaps with isna() (modules 24 and 26).

P4-02 · Fix the bugs: a churn table by tenure band

Section titled “P4-02 · Fix the bugs: a churn table by tenure band”
Warm-up

Fix the bugs: the retention team wants three numbers from data/customers.csv. They want the customers per tenure band (0–6, 7–24 and 25–72 months), the churn rate in each band and the churn rate of month-to-month customers in their first 6 months. The code below runs without an error, but it has three bugs:

customers = pd.read_csv("data/customers.csv")
customers["band"] = pd.cut(
customers["tenure_months"], bins=[0, 6, 24, 72], labels=["0-6", "7-24", "25-72"]
)
counts = customers["band"].value_counts(sort=False)
print(counts.to_dict(), "total", counts.sum())
rates = pd.crosstab(customers["band"], customers["churned"], normalize="columns")
print("churn % per band:", (rates[1] * 100).round(1).to_dict())
risky = customers[
(customers["contract"] == "month-to-month") | (customers["band"] == "0-6")
]
print(f"{len(risky)} risky customers, churn {risky['churned'].mean():.1%}")
Output
{'0-6': 1100, '7-24': 2049, '25-72': 1841} total 4990
churn % per band: {'0-6': 50.7, '7-24': 35.0, '25-72': 14.3}
2887 risky customers, churn 29.1%

Fix it so that it prints the lines below. Every customer must be in a band.

Expected output
{'0-6': 1110, '7-24': 2049, '25-72': 1841} total 5000
churn % per band: {'0-6': 44.0, '7-24': 16.4, '25-72': 7.5}
1007 risky customers, churn 46.9%
Starter
customers = pd.read_csv("data/customers.csv")
customers["band"] = pd.cut(
customers["tenure_months"], bins=[0, 6, 24, 72], labels=["0-6", "7-24", "25-72"]
)
counts = customers["band"].value_counts(sort=False)
print(counts.to_dict(), "total", counts.sum())
rates = pd.crosstab(customers["band"], customers["churned"], normalize="columns")
print("churn % per band:", (rates[1] * 100).round(1).to_dict())
risky = customers[
(customers["contract"] == "month-to-month") | (customers["band"] == "0-6")
]
print(f"{len(risky)} risky customers, churn {risky['churned'].mean():.1%}")
# TODO: find and fix the three bugs
Hint 1

The total is 4,990, not 5,000. pd.cut uses intervals that are open on the left by default: (0, 6]. Where does a customer with tenure_months 0 go?

Hint 2

normalize="columns" divides each cell by its column total. It answers “of all churners, which share is in each band?”. The churn rate of a band divides by the row total.

Hint 3

Count the risky customers who are not month-to-month. Should there be any?

Solution
customers = pd.read_csv("data/customers.csv")
customers["band"] = pd.cut(
customers["tenure_months"],
bins=[0, 6, 24, 72],
labels=["0-6", "7-24", "25-72"],
include_lowest=True,
)
counts = customers["band"].value_counts(sort=False)
print(counts.to_dict(), "total", counts.sum())
rates = pd.crosstab(customers["band"], customers["churned"], normalize="index")
print("churn % per band:", (rates[1] * 100).round(1).to_dict())
risky = customers[
(customers["contract"] == "month-to-month") & (customers["band"] == "0-6")
]
print(f"{len(risky)} risky customers, churn {risky['churned'].mean():.1%}")
assert counts.sum() == len(customers) == 5000
assert np.isclose(rates.sum(axis=1), 1).all()
assert risky["contract"].eq("month-to-month").all()
Output
{'0-6': 1110, '7-24': 2049, '25-72': 1841} total 5000
churn % per band: {'0-6': 44.0, '7-24': 16.4, '25-72': 7.5}
1007 risky customers, churn 46.9%

How it works:

  1. Bug 1: pd.cut with bins=[0, 6, ...] builds the interval (0, 6], so the 10 brand-new customers with tenure_months 0 get NaN and drop out of value_counts. include_lowest=True closes the first interval on the left. Always check that the band counts add up to the row count (module 26).
  2. Bug 2: normalize="index" divides by the row total, so each row (band) adds up to 1 and column 1 is the churn rate. With "columns", the old “rates” were shares of all churners: they also added up to 100% across the bands, which is a sign of the bug (module 27).
  3. Bug 3: | keeps a customer who matches either condition, so 2,887 customers passed. & keeps the 1,007 customers who match both (module 24).
  4. The 0–6 band reads 44.0%. The data dictionary gives 44.4% for 1–6 months. The difference is the 10 customers with tenure 0, who never churned.

P4-03 · Write the code: Q4 category ranks with SQL windows

Section titled “P4-03 · Write the code: Q4 category ranks with SQL windows”
Warm-up

Write the code: the finance team wants one table for Q4 of both years. Per year and category, it shows the lines, the revenue, the share of that year’s revenue, the rank inside the year and the growth against the same category one year earlier. Write category_report(first_month, last_month). It opens data/shop.db read-only, joins orders to products and computes everything in one SQL query: a CTE for the totals, then window functions with PARTITION BY for the share, RANK() and LAG(). Pass the months with ? placeholders, never with an f-string. Then check the revenue against data/sales.csv with pandas.

Expected output
year category lines revenue share_pct rank growth_pct
2023 Electronics 707 320297.66 57.3 1 NaN
2023 Home 527 98176.97 17.6 2 NaN
2023 Sports 344 54336.61 9.7 3 NaN
2023 Clothing 623 48163.09 8.6 4 NaN
2023 Beauty 448 20931.32 3.7 5 NaN
2023 Books 382 16750.79 3.0 6 NaN
2024 Electronics 905 392365.71 53.2 1 22.5
2024 Home 667 153046.18 20.8 2 55.9
2024 Sports 451 75771.88 10.3 3 39.4
2024 Clothing 836 64773.05 8.8 4 34.5
2024 Beauty 622 32375.38 4.4 5 54.7
2024 Books 493 19194.04 2.6 6 14.6
Q4 2024 revenue: 737,526.24
Starter
SQL = """
WITH totals AS (
SELECT ...
FROM orders AS o
JOIN products AS p ON p.product_id = o.product_id
WHERE ...
GROUP BY year, p.category
)
SELECT ...
FROM totals
ORDER BY year, rank
"""
def category_report(first_month: str, last_month: str) -> pd.DataFrame:
"""Lines, revenue, share, rank and growth per category and year."""
# TODO: open data/shop.db read-only, run SQL with the two months, close
# TODO: print the report for months "10" to "12"
# TODO: recompute the revenue per year and category in pandas and assert they match
Hint 1

sqlite3.connect("file:data/shop.db?mode=ro", uri=True) opens the file read-only. strftime('%Y', order_date) and strftime('%m', order_date) give the year and the month as text, so BETWEEN '10' AND '12' works.

Hint 2

A window runs after GROUP BY. SUM(revenue) OVER (PARTITION BY year) is the total of the year, RANK() OVER (PARTITION BY year ORDER BY revenue DESC) the position inside the year, and LAG(revenue) OVER (PARTITION BY category ORDER BY year) the same category one year earlier.

Solution
SQL = """
WITH totals AS (
SELECT strftime('%Y', o.order_date) AS year,
p.category,
COUNT(*) AS lines,
SUM(o.revenue) AS revenue
FROM orders AS o
JOIN products AS p ON p.product_id = o.product_id
WHERE strftime('%m', o.order_date) BETWEEN ? AND ?
GROUP BY year, p.category
)
SELECT year, category, lines,
ROUND(revenue, 2) AS revenue,
ROUND(100.0 * revenue / SUM(revenue) OVER (PARTITION BY year), 1) AS share_pct,
RANK() OVER (PARTITION BY year ORDER BY revenue DESC) AS rank,
ROUND(100.0 * (revenue / LAG(revenue) OVER (
PARTITION BY category ORDER BY year) - 1), 1) AS growth_pct
FROM totals
ORDER BY year, rank
"""
def category_report(first_month: str, last_month: str) -> pd.DataFrame:
"""Lines, revenue, share, rank and growth per category and year."""
con = sqlite3.connect("file:data/shop.db?mode=ro", uri=True)
try:
return pd.read_sql_query(SQL, con, params=(first_month, last_month))
finally:
con.close()
report = category_report("10", "12")
print(report.to_string(index=False))
sales = pd.read_csv("data/sales.csv")
q4 = sales[sales["order_date"].str[5:7].between("10", "12")]
check = q4.groupby([q4["order_date"].str[:4], "category"])["revenue"].sum()
merged = report.set_index(["year", "category"])["revenue"]
print(f"Q4 2024 revenue: {merged.loc['2024'].sum():,.2f}")
assert np.allclose(merged.sort_index(), check.sort_index(), atol=0.01)
assert report["growth_pct"].isna().sum() == 6
assert np.allclose(report.groupby("year")["share_pct"].sum(), 100, atol=0.2)
Output
year category lines revenue share_pct rank growth_pct
2023 Electronics 707 320297.66 57.3 1 NaN
2023 Home 527 98176.97 17.6 2 NaN
2023 Sports 344 54336.61 9.7 3 NaN
2023 Clothing 623 48163.09 8.6 4 NaN
2023 Beauty 448 20931.32 3.7 5 NaN
2023 Books 382 16750.79 3.0 6 NaN
2024 Electronics 905 392365.71 53.2 1 22.5
2024 Home 667 153046.18 20.8 2 55.9
2024 Sports 451 75771.88 10.3 3 39.4
2024 Clothing 836 64773.05 8.8 4 34.5
2024 Beauty 622 32375.38 4.4 5 54.7
2024 Books 493 19194.04 2.6 6 14.6
Q4 2024 revenue: 737,526.24

How it works:

  1. The ? placeholders send the months as values. The database never reads them as SQL, so a value typed by a user cannot change the query (module 30).
  2. The CTE totals collapses the order lines to one row per year and category. The outer query adds the windows to these 12 rows without collapsing them.
  3. PARTITION BY year restarts the share and the rank for each year. PARTITION BY category ORDER BY year makes LAG look one year back in the same category. In 2023 there is no earlier row, so the growth is NULL, which pandas shows as NaN.
  4. try/finally closes the connection even when the query fails. mode=ro makes sure that no exercise can change the course data.
  5. The pandas check groups the other copy of the data by year and category. Both results are sorted by their index before the comparison, with a tolerance of 0.01, as the data dictionary advises (module 25).
  6. Electronics brings 53.2% of Q4 2024 revenue, but its share fell from 57.3%. Home and Beauty grew fastest, by 55.9% and 54.7%.

P4-04 · Fix the bugs: a cleaning script that passes but lies

Section titled “P4-04 · Fix the bugs: a cleaning script that passes but lies”
Core

Fix the bugs: a colleague cleans data/sales_raw.csv with the function below. It runs without an error, and reconcile() compares the result with data/sales.csv, which holds the correct values of the same lines. The report shows four problems: lost rows, missing prices, wrong dates and a region that is not a region. Find the four bugs and fix them. Keep reconcile() as it is.

def clean(raw: pd.DataFrame) -> pd.DataFrame:
df = raw.drop_duplicates(subset=["order_id"])
df["order_date"] = pd.to_datetime(df["order_date"], format="mixed", dayfirst=True)
df["region"] = df["region"].str.strip().str.title()
price = df["unit_price"].str.replace("$", "")
df["unit_price"] = pd.to_numeric(price, errors="coerce")
return df
def reconcile(df: pd.DataFrame) -> None:
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
both = df.merge(sales, on=["order_id", "product_id"], suffixes=("", "_ref"),
validate="1:1")
known = both["unit_price"].notna()
print("rows:", len(df), "| matched in sales.csv:", len(both))
print("missing unit_price:", int(df["unit_price"].isna().sum()))
print("wrong dates:", int((both["order_date"] != both["order_date_ref"]).sum()))
wrong = both.loc[known, "unit_price"] != both.loc[known, "unit_price_ref"]
print("wrong prices:", int(wrong.sum()))
print("regions:", sorted(df["region"].dropna().unique()))
raw = pd.read_csv("data/sales_raw.csv")
reconcile(clean(raw))
Output
rows: 1148 | matched in sales.csv: 1148
missing unit_price: 52
wrong dates: 254
wrong prices: 0
regions: ['-', 'East', 'North', 'South', 'West']

After the fix, the report must read:

Expected output
rows: 1164 | matched in sales.csv: 1164
missing unit_price: 9
wrong dates: 0
wrong prices: 0
regions: ['East', 'North', 'South', 'West']
Starter
def clean(raw: pd.DataFrame) -> pd.DataFrame:
df = raw.drop_duplicates(subset=["order_id"])
df["order_date"] = pd.to_datetime(df["order_date"], format="mixed", dayfirst=True)
df["region"] = df["region"].str.strip().str.title()
price = df["unit_price"].str.replace("$", "")
df["unit_price"] = pd.to_numeric(price, errors="coerce")
return df
# reconcile() as above
raw = pd.read_csv("data/sales_raw.csv")
reconcile(clean(raw))
# TODO: fix the four bugs in clean() and in the read_csv call
Hint 1

Is order_id a key of the sales lines? Look at the data dictionary: one order has 1–3 lines.

Hint 2

Print a few of the prices that became NaN, and the rows where the date differs from the reference. What do they have in common?

Hint 3

Which missing-value tokens does pd.read_csv know by default? - is not one of them.

Solution
def clean(raw: pd.DataFrame) -> pd.DataFrame:
df = raw.drop_duplicates()
text = df["order_date"].str.strip()
dates = pd.to_datetime(text, format="%Y-%m-%d", errors="coerce")
for fmt in ["%d/%m/%Y", "%B %d, %Y"]:
dates = dates.fillna(pd.to_datetime(text, format=fmt, errors="coerce"))
df["order_date"] = dates
df["region"] = df["region"].str.strip().str.title()
price = df["unit_price"].str.replace(r"[$,]", "", regex=True)
df["unit_price"] = pd.to_numeric(price)
return df
def reconcile(df: pd.DataFrame) -> None:
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
both = df.merge(sales, on=["order_id", "product_id"], suffixes=("", "_ref"),
validate="1:1")
known = both["unit_price"].notna()
print("rows:", len(df), "| matched in sales.csv:", len(both))
print("missing unit_price:", int(df["unit_price"].isna().sum()))
print("wrong dates:", int((both["order_date"] != both["order_date_ref"]).sum()))
wrong = both.loc[known, "unit_price"] != both.loc[known, "unit_price_ref"]
print("wrong prices:", int(wrong.sum()))
print("regions:", sorted(df["region"].dropna().unique()))
raw = pd.read_csv(
"data/sales_raw.csv", keep_default_na=False, na_values=["", "N/A", "-"]
)
df = clean(raw)
reconcile(df)
assert len(df) == 1164 and not df.duplicated(["order_id", "product_id"]).any()
assert df["order_date"].notna().all()
assert set(df["region"].dropna()) == {"East", "North", "South", "West"}
Output
rows: 1164 | matched in sales.csv: 1164
missing unit_price: 9
wrong dates: 0
wrong prices: 0
regions: ['East', 'North', 'South', 'West']

How it works:

  1. Bug 1: drop_duplicates(subset=["order_id"]) keeps only the first line of each order, so 16 real lines of multi-line orders disappeared. The file’s duplicates are exact copies, so drop_duplicates() without subset removes the 36 copies and nothing else. The assert checks the real key, (order_id, product_id) (module 26).
  2. Bug 2: format="mixed" guesses the format of each value. With dayfirst=True, it reads ISO dates such as 2023-01-04 as year-day-month, which gave 254 wrong dates. Without dayfirst, it swaps the DD/MM/YYYY dates instead. Parse each of the three known formats strictly with errors="coerce" and combine them with fillna.
  3. Bug 3: "$1,299.00" still has a comma after the dollar sign is removed, and errors="coerce" turned these prices into NaN without a word. The regex [$,] removes both characters. Without errors="coerce", any other junk raises an error, which is what a cleaning step should do (module 24).
  4. Bug 4: - is a missing-value token in this file, but read_csv does not know it. Declare all three with keep_default_na=False, na_values=["", "N/A", "-"]. After the fix, the 9 missing prices are real gaps, not parse failures.
  5. The reconciliation is the proof: all 1,164 lines are found, and no known date or price differs from the reference. A cleaning step that only “runs” proves nothing.

P4-05 · Write the code: check the API catalog and hand it over in Excel

Section titled “P4-05 · Write the code: check the API catalog and hand it over in Excel”
Core

Write the code: the shop’s product API was saved as three JSON pages in data/api/. The category managers want the catalog in an Excel file, but first you must prove that the API agrees with the shop’s own data. Load the three pages, flatten the nested price and rating objects and stack the pages into one table indexed by product id. Join it with data/products.csv and with the mean rating and the review count per product from data/reviews.csv. Count the mismatches of price, rating (1 decimal) and count. List the products that are out of stock with query. Add the units sold per product with map, and an ordered price band (budget up to 50 USD, mid up to 200 USD, premium above). Summarize per band. Write the catalog and the summary to two sheets of output/catalog.xlsx and read the file back. Finally, load the catalog into an in-memory SQLite database and find the best-selling product of each band with RANK().

Expected output
rows: 30 | columns: name, category, in_stock, stock, launch_date, url, price_amount ...
mismatches against the shop data: {'price': 0, 'rating': 0, 'count': 0}
out of stock: ['P006', 'P019']
products units rating
band
budget 12 13947 3.85
mid 12 11864 3.84
premium 6 3722 3.88
{'catalog': (30, 13), 'by_band': (3, 4)}
band name units
budget Organic Cotton T-Shirt 1885
mid Wireless Earbuds 1551
premium Noise-Cancelling Headphones 966
Starter
import json
from pathlib import Path
pages = []
for number in [1, 2, 3]:
... # TODO: json.load each page and flatten payload["data"]
catalog = ... # TODO: one table of 30 rows, indexed by id
# TODO: join with products.csv and the review summary; count mismatches
# TODO: out-of-stock ids; units with map; ordered price band; summary per band
# TODO: two sheets in output/catalog.xlsx; read back with sheet_name=None
# TODO: to_sql into sqlite3.connect(":memory:"); RANK() per band; print the top
Hint 1

pd.json_normalize(payload["data"], sep="_") turns {"price": {"amount": 79.99}} into a column price_amount. pd.concat(pages, ignore_index=True) stacks the three pages.

Hint 2

catalog.join(other) matches on the index, so give both tables the product id as their index. pd.cut(..., labels=[...], ordered=True) makes an ordered categorical, and groupby("band", observed=False) keeps a band even if it were empty.

Hint 3

df.to_sql("catalog", con, index=False) writes a DataFrame to SQL. SQLite has no categorical type: convert the band to text first. Filter on a window result in an outer query, because WHERE runs before the window.

Solution
import json
from pathlib import Path
pages = []
for number in [1, 2, 3]:
with open(f"data/api/products_page_{number}.json", encoding="utf-8") as file:
payload = json.load(file)
pages.append(pd.json_normalize(payload["data"], sep="_"))
catalog = pd.concat(pages, ignore_index=True).set_index("id")
print("rows:", len(catalog), "| columns:", ", ".join(catalog.columns[:7]), "...")
products = pd.read_csv("data/products.csv", index_col="product_id")
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)
sales = pd.read_csv("data/sales.csv")
truth = reviews.groupby("product_id")["rating"].agg(["mean", "size"])
check = catalog.join(products[["unit_price"]]).join(truth, validate="1:1")
mismatch = {
"price": int((check["price_amount"] != check["unit_price"]).sum()),
"rating": int((check["rating_average"] != check["mean"].round(1)).sum()),
"count": int((check["rating_count"] != check["size"]).sum()),
}
print("mismatches against the shop data:", mismatch)
print("out of stock:", catalog.query("stock == 0").index.tolist())
catalog["units"] = catalog.index.map(sales.groupby("product_id")["quantity"].sum())
catalog["band"] = pd.cut(
catalog["price_amount"],
bins=[0, 50, 200, 2000],
labels=["budget", "mid", "premium"],
ordered=True,
)
by_band = catalog.groupby("band", observed=False).agg(
products=("name", "size"), units=("units", "sum"), rating=("rating_average", "mean")
)
print(by_band.round(2).to_string())
Path("output").mkdir(exist_ok=True)
with pd.ExcelWriter("output/catalog.xlsx") as writer:
catalog.to_excel(writer, sheet_name="catalog")
by_band.to_excel(writer, sheet_name="by_band")
sheets = pd.read_excel("output/catalog.xlsx", sheet_name=None)
print({name: frame.shape for name, frame in sheets.items()})
con = sqlite3.connect(":memory:")
catalog.reset_index().assign(band=catalog["band"].astype(str).to_numpy()).to_sql(
"catalog", con, index=False
)
top = pd.read_sql_query(
"""
SELECT band, name, units
FROM (
SELECT band, name, units,
RANK() OVER (PARTITION BY band ORDER BY units DESC) AS pos
FROM catalog
)
WHERE pos = 1
ORDER BY units DESC
""",
con,
)
con.close()
print(top.to_string(index=False))
assert len(catalog) == 30 and catalog.index.is_unique
assert sum(mismatch.values()) == 0
assert list(sheets) == ["catalog", "by_band"]
assert by_band["products"].sum() == 30
Output
rows: 30 | columns: name, category, in_stock, stock, launch_date, url, price_amount ...
mismatches against the shop data: {'price': 0, 'rating': 0, 'count': 0}
out of stock: ['P006', 'P019']
products units rating
band
budget 12 13947 3.85
mid 12 11864 3.84
premium 6 3722 3.88
{'catalog': (30, 13), 'by_band': (3, 4)}
band name units
budget Organic Cotton T-Shirt 1885
mid Wireless Earbuds 1551
premium Noise-Cancelling Headphones 966

How it works:

  1. json_normalize flattens one level of nesting per object, and sep="_" builds names such as rating_average. concat stacks the pages; ignore_index=True gives a fresh index before set_index("id") (modules 24 and 25).
  2. The two join calls match on the product id. validate="1:1" makes sure that the review summary has one row per product. All 30 prices, ratings and counts agree, so the API can be trusted for this hand-over.
  3. query("stock == 0") reads like the question. P006 and P019 are out of stock, as the data dictionary says.
  4. map with a Series looks up the units of each product id: a vectorized lookup, not an apply with a Python function. The ordered band sorts as budget < mid < premium, not alphabetically.
  5. ExcelWriter writes several sheets into one file. read_excel(..., sheet_name=None) returns a dict of all sheets, which proves that both arrived. The catalog sheet has 13 columns: the 12 catalog columns and the index.
  6. to_sql moves the pandas table into SQL. RANK() OVER (PARTITION BY band ORDER BY units DESC) ranks inside each band, and the outer query keeps rank 1 (module 30). Budget products sell most units, and the budget T-shirt is the overall best seller.

P4-06 · Write the code: do weekends sell more?

Section titled “P4-06 · Write the code: do weekends sell more?”
Core

Write the code: the store managers want to move staff from weekdays to weekends. They ask how much more the shop sells per weekend day. Use Polars for the data work: aggregate data/sales.csv to daily revenue in a lazy query, label each day weekday or weekend with when/then/otherwise and summarize days, mean, median and skewness per label. Then compare the two groups with a Welch t-test and a Mann–Whitney U test. Report the probability that a random weekend day beats a random weekday, and a 95% bootstrap CI for the ratio of the medians (5,000 resamples, default_rng(42)). Draw a box plot with the y axis in thousands and point to the largest day. Which number would you give the managers?

Expected output
shape: (2, 5)
┌──────────┬──────┬────────┬────────┬──────┐
│ day_type ┆ days ┆ mean ┆ median ┆ skew │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ f64 ┆ f64 ┆ f64 │
╞══════════╪══════╪════════╪════════╪══════╡
│ weekday ┆ 522 ┆ 4488.0 ┆ 3810.0 ┆ 3.77 │
│ weekend ┆ 209 ┆ 5999.0 ┆ 5343.0 ┆ 1.04 │
└──────────┴──────┴────────┴────────┴──────┘
Welch t = 6.12, p = 2.3e-09
Mann-Whitney p = 1.0e-13, P(weekend > weekday) = 0.676
median ratio 1.40, 95% bootstrap CI 1.26 to 1.58
Starter
from matplotlib.ticker import FuncFormatter
daily = (
pl.scan_csv("data/sales.csv", try_parse_dates=True)
# TODO: revenue per order_date, day_type with when/then/otherwise
.collect()
)
# TODO: summary per day_type: days, mean, median (0 decimals), skew (2 decimals)
# TODO: Welch t-test, Mann-Whitney U and P(weekend > weekday)
# TODO: bootstrap CI for median(weekend) / median(weekday)
# TODO: box plot, k formatter, annotate the largest day; plt.show()
Hint 1

In Polars, dt.weekday() returns 1 for Monday and 7 for Sunday. pl.len() counts the rows of a group, and .sort("day_type") makes the order of the result stable.

Hint 2

The Mann–Whitney statistic U divided by n_weekend * n_weekday is the probability that a random weekend day has more revenue than a random weekday. For the bootstrap, rng.choice(values, size=(5000, values.size)) draws all resamples at once; take np.median(..., axis=1).

Solution
from matplotlib.ticker import FuncFormatter
daily = (
pl.scan_csv("data/sales.csv", try_parse_dates=True)
.group_by("order_date")
.agg(pl.col("revenue").sum())
.with_columns(
day_type=pl.when(pl.col("order_date").dt.weekday() >= 6)
.then(pl.lit("weekend"))
.otherwise(pl.lit("weekday"))
)
.sort("order_date")
.collect()
)
summary = (
daily.group_by("day_type")
.agg(
days=pl.len(),
mean=pl.col("revenue").mean().round(0),
median=pl.col("revenue").median().round(0),
skew=pl.col("revenue").skew().round(2),
)
.sort("day_type")
)
print(summary)
weekday = daily.filter(pl.col("day_type") == "weekday")["revenue"].to_numpy()
weekend = daily.filter(pl.col("day_type") == "weekend")["revenue"].to_numpy()
welch = stats.ttest_ind(weekend, weekday, equal_var=False)
mwu = stats.mannwhitneyu(weekend, weekday, alternative="two-sided")
superiority = mwu.statistic / (weekend.size * weekday.size)
print(f"Welch t = {welch.statistic:.2f}, p = {welch.pvalue:.1e}")
print(f"Mann-Whitney p = {mwu.pvalue:.1e}, P(weekend > weekday) = {superiority:.3f}")
rng = np.random.default_rng(42)
boot_end = np.median(rng.choice(weekend, size=(5000, weekend.size)), axis=1)
boot_day = np.median(rng.choice(weekday, size=(5000, weekday.size)), axis=1)
low, high = np.percentile(boot_end / boot_day, [2.5, 97.5])
ratio = np.median(weekend) / np.median(weekday)
print(f"median ratio {ratio:.2f}, 95% bootstrap CI {low:.2f} to {high:.2f}")
fig, ax = plt.subplots(figsize=(6, 4))
ax.boxplot([weekday, weekend], tick_labels=["Mon–Fri", "Sat–Sun"])
ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: f"{v / 1000:.0f}k"))
top = daily.sort("revenue", descending=True).row(0, named=True)
ax.annotate(
f"Black Friday {top['order_date']}",
xy=(1, top["revenue"]),
xytext=(1.3, 25_000),
arrowprops={"arrowstyle": "->", "color": "black"},
)
ax.set(
title="Weekend days earn about 40% more (median)",
ylabel="Daily revenue (USD)",
)
assert summary["days"].to_list() == [522, 209]
assert welch.pvalue < 0.001 and mwu.pvalue < 0.001
assert 1 < low < ratio < high
plt.show()
Output
shape: (2, 5)
┌──────────┬──────┬────────┬────────┬──────┐
│ day_type ┆ days ┆ mean ┆ median ┆ skew │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ f64 ┆ f64 ┆ f64 │
╞══════════╪══════╪════════╪════════╪══════╡
│ weekday ┆ 522 ┆ 4488.0 ┆ 3810.0 ┆ 3.77 │
│ weekend ┆ 209 ┆ 5999.0 ┆ 5343.0 ┆ 1.04 │
└──────────┴──────┴────────┴────────┴──────┘
Welch t = 6.12, p = 2.3e-09
Mann-Whitney p = 1.0e-13, P(weekend > weekday) = 0.676
median ratio 1.40, 95% bootstrap CI 1.26 to 1.58
Box plots of daily revenue: the weekday median is about 3,800 USD with many high outliers up to Black Friday at 33,600 USD; the weekend median is about 5,300 USD.
Daily revenue on weekdays and weekend days, 2023–2024.

How it works:

  1. The lazy query reads only the two columns it needs. group_by has no stable order, so the query sorts by date (module 31).
  2. Weekday revenue has a skewness of 3.77: promo days such as Black Friday are Fridays. The means are pulled up by these days, so the medians describe a typical day better (module 27).
  3. Both tests reject “no difference” clearly. Welch does not assume equal variances. Mann–Whitney uses ranks, so the Black Friday outliers do not dominate it. A weekend day beats a weekday 67.6% of the time (module 29).
  4. The bootstrap gives a CI for any statistic: the median weekend day earns 1.40 times the median weekday, and plausibly between 1.26 and 1.58 times.
  5. The managers need the effect size, not the p-value: “A typical weekend day sells about 40% more than a typical weekday (95% CI: 26% to 58%). Plan staff for that ratio, and plan promo days separately.”

P4-07 · Interpret a result: does autopay reduce churn?

Section titled “P4-07 · Interpret a result: does autopay reduce churn?”
Core

Interpret a result: a colleague’s slide says, “Customers with autopay churn 5 points less. Push autopay to everyone.” Check the claim on data/customers.csv. Compute the churn rate with and without autopay and test the gap with a chi-square test. Then split by payment method: churn with and without autopay, the gap in percentage points, the autopay share and the number of customers per method. Compute the size-weighted gap within the methods. Fit two linear probability models with smf.ols and HC3 standard errors: autopay alone, and autopay plus payment method. Draw the churn rates per method and autopay status. Then answer: is the raw gap real, is it caused by autopay, and what do you tell the team?

Expected output
churn: no autopay 21.9%, autopay 16.9%, p = 1.2e-05
no_autopay autopay diff_pp autopay_share n
payment_method
electronic_check 0.257 0.200 -5.666 0.160 1563
bank_transfer 0.186 0.171 -1.583 0.805 1209
credit_card 0.175 0.153 -2.198 0.756 1360
paypal 0.160 0.190 3.002 0.454 868
size-weighted gap within payment methods: -2.2 pp
raw: -4.9 pp [-7.1, -2.7], p = 1.1e-05
adjusted: -1.6 pp [-4.2, +1.0], p = 0.22
Starter
customers = pd.read_csv("data/customers.csv")
# TODO: churn rate by has_autopay, chi-square p-value
# TODO: pivot_table by payment_method x has_autopay, diff_pp, autopay_share, n
# TODO: size-weighted gap within payment methods
# TODO: OLS raw and adjusted, coefficient in pp with 95% CI and p-value
# TODO: bar chart by payment method and autopay with 95% CIs; plt.show()
Hint 1

A confounder is linked to both the “cause” and the outcome. Look at the autopay share per payment method, and at the churn rate per payment method.

Hint 2

A linear probability model is OLS on a 0/1 target: the coefficient is a difference in churn rate. C(payment_method) adds one dummy per method, so the autopay coefficient compares customers with the same method. Use fit(cov_type="HC3"), because a 0/1 target has unequal variances.

Solution
customers = pd.read_csv("data/customers.csv")
raw = customers.groupby("has_autopay")["churned"].mean()
_, p_raw, _, _ = stats.chi2_contingency(
pd.crosstab(customers["has_autopay"], customers["churned"])
)
print(f"churn: no autopay {raw[0]:.1%}, autopay {raw[1]:.1%}, p = {p_raw:.1e}")
strata = customers.pivot_table(
index="payment_method", columns="has_autopay", values="churned", aggfunc="mean"
)
strata.columns = ["no_autopay", "autopay"]
strata["diff_pp"] = (strata["autopay"] - strata["no_autopay"]) * 100
strata["autopay_share"] = customers.groupby("payment_method")["has_autopay"].mean()
strata["n"] = customers["payment_method"].value_counts()
strata = strata.sort_values("no_autopay", ascending=False)
print(strata.round(3).to_string())
weighted = np.average(strata["diff_pp"], weights=strata["n"])
print(f"size-weighted gap within payment methods: {weighted:+.1f} pp")
models = {
"raw": "churned ~ has_autopay",
"adjusted": "churned ~ has_autopay + C(payment_method)",
}
for name, formula in models.items():
fit = smf.ols(formula, data=customers).fit(cov_type="HC3")
low, high = fit.conf_int().loc["has_autopay"] * 100
print(
f"{name:>8}: {fit.params['has_autopay'] * 100:+.1f} pp "
f"[{low:+.1f}, {high:+.1f}], p = {fit.pvalues['has_autopay']:.2g}"
)
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
sns.barplot(
data=customers.assign(autopay=customers["has_autopay"].map({0: "No", 1: "Yes"})),
x="payment_method",
y="churned",
hue="autopay",
hue_order=["No", "Yes"],
order=strata.index,
errorbar=("ci", 95),
seed=42,
ax=ax,
)
ax.set(
title="Most of the autopay gap is the payment-method mix",
xlabel="Payment method",
ylabel="Churn rate (95% CI)",
)
ax.legend(title="Autopay")
assert p_raw < 0.001
assert strata["autopay_share"].idxmin() == "electronic_check"
assert abs(weighted) < abs(raw[1] - raw[0]) * 100
plt.show()
Output
churn: no autopay 21.9%, autopay 16.9%, p = 1.2e-05
no_autopay autopay diff_pp autopay_share n
payment_method
electronic_check 0.257 0.200 -5.666 0.160 1563
bank_transfer 0.186 0.171 -1.583 0.805 1209
credit_card 0.175 0.153 -2.198 0.756 1360
paypal 0.160 0.190 3.002 0.454 868
size-weighted gap within payment methods: -2.2 pp
raw: -4.9 pp [-7.1, -2.7], p = 1.1e-05
adjusted: -1.6 pp [-4.2, +1.0], p = 0.22
Grouped bars of churn rate per payment method with and without autopay: electronic check has the highest churn and keeps a 6-point gap, the bars are close for bank transfer and credit card, and for PayPal churn with autopay is higher.
Churn rate by payment method and autopay, with 95% bootstrap CIs.

How it works:

  1. The raw gap is real in the sense of “not chance”: 21.9% against 16.9%, p = 1.2e-05.
  2. Electronic check has the highest churn (25.7% without autopay) and the lowest autopay share (16%). Customers who pay by electronic check rarely use autopay and churn often for other reasons. So the raw comparison mixes the effect of autopay with the effect of the payment method (module 27).
  3. Within the methods, the gaps range from −5.7 points (electronic check) to +3.0 points (PayPal). Weighted by size, they average −2.2 points. The adjusted OLS model gives −1.6 points with a 95% CI from −4.2 to +1.0: it includes zero (module 29).
  4. The chart shows the same thing: the pairs are close for bank transfer and credit card, PayPal reverses, and only electronic check keeps a clear gap, with a wide error bar for its few autopay customers (module 28).

What to tell the team: “The 5-point gap is mostly the payment-method mix: electronic-check customers churn more and rarely use autopay. Among customers with the same payment method, autopay is linked to about 2 points less churn, and zero is plausible. This is observational data, so even 2 points is not proof of an effect. If autopay matters, test it: offer autopay to a random half of new electronic-check customers and compare churn.”

P4-08 · Refactor: one customer summary, three engines

Section titled “P4-08 · Refactor: one customer summary, three engines”
Core

Refactor: the nightly job below builds a summary per customer with iterrows: distinct orders, revenue and the days between the first and the last order. Keep it as the reference. Write the same summary three times: with pandas named aggregation, with a DuckDB query on the DataFrame and with Polars. Prove that each version equals the loop with pd.testing.assert_frame_equal, and time the loop against pandas with time.perf_counter. Then print the top 3 customers by revenue (tie-breaker customer_id) and the revenue share of the top 10% of buyers. Which engine would you choose for the nightly job, and why?

Expected output
loop at least 10 times slower than pandas: True
summary_pandas: 3254 customers, matches the loop
summary_duckdb: 3254 customers, matches the loop
summary_polars: 3254 customers, matches the loop
customer_id orders revenue active_days
C01364 44 16023.65 706
C01766 36 13341.26 719
C01656 24 12785.14 714
top 10% of buyers (325) bring 40.5% of revenue
Starter
def summary_loop(sales: pd.DataFrame) -> pd.DataFrame:
"""The old version: one Python step per order line."""
acc: dict[str, dict] = {}
for _, row in sales.iterrows():
c = acc.setdefault(
row["customer_id"],
{"orders": set(), "revenue": 0.0,
"first": row["order_date"], "last": row["order_date"]},
)
c["orders"].add(row["order_id"])
c["revenue"] += row["revenue"]
c["first"] = min(c["first"], row["order_date"])
c["last"] = max(c["last"], row["order_date"])
rows = [
(cid, len(c["orders"]), round(c["revenue"], 2), (c["last"] - c["first"]).days)
for cid, c in acc.items()
]
columns = ["customer_id", "orders", "revenue", "active_days"]
out = pd.DataFrame(rows, columns=columns)
return out.sort_values("customer_id", ignore_index=True)
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
reference = summary_loop(sales)
# TODO: summary_pandas, summary_duckdb, summary_polars; compare each with reference
# TODO: time the loop and pandas; print whether the loop is 10 times slower
# TODO: top 3 by revenue, revenue share of the top 10% of buyers
Hint 1

pandas: groupby("customer_id").agg(orders=("order_id", "nunique"), ...), then subtract the min and max dates and take .dt.days. DuckDB: COUNT(DISTINCT order_id) and date_diff('day', MIN(order_date), MAX(order_date)), run on the DataFrame by its variable name.

Hint 2

Polars: pl.from_pandas(sales), then n_unique(), and (max - min).dt.total_days() for the span. group_by results have no fixed order in DuckDB or Polars: sort by customer_id before you compare. Pass check_dtype=False, because each engine picks its own integer type.

Solution
import time
def summary_loop(sales: pd.DataFrame) -> pd.DataFrame:
"""The old version: one Python step per order line."""
acc: dict[str, dict] = {}
for _, row in sales.iterrows():
c = acc.setdefault(
row["customer_id"],
{"orders": set(), "revenue": 0.0,
"first": row["order_date"], "last": row["order_date"]},
)
c["orders"].add(row["order_id"])
c["revenue"] += row["revenue"]
c["first"] = min(c["first"], row["order_date"])
c["last"] = max(c["last"], row["order_date"])
rows = [
(cid, len(c["orders"]), round(c["revenue"], 2), (c["last"] - c["first"]).days)
for cid, c in acc.items()
]
columns = ["customer_id", "orders", "revenue", "active_days"]
out = pd.DataFrame(rows, columns=columns)
return out.sort_values("customer_id", ignore_index=True)
def summary_pandas(sales: pd.DataFrame) -> pd.DataFrame:
return (
sales.groupby("customer_id")
.agg(
orders=("order_id", "nunique"),
revenue=("revenue", "sum"),
first=("order_date", "min"),
last=("order_date", "max"),
)
.assign(
revenue=lambda d: d["revenue"].round(2),
active_days=lambda d: (d["last"] - d["first"]).dt.days,
)
.drop(columns=["first", "last"])
.reset_index()
)
def summary_duckdb(sales: pd.DataFrame) -> pd.DataFrame:
return duckdb.sql("""
SELECT customer_id,
COUNT(DISTINCT order_id) AS orders,
ROUND(SUM(revenue), 2) AS revenue,
date_diff('day', MIN(order_date), MAX(order_date)) AS active_days
FROM sales
GROUP BY customer_id
ORDER BY customer_id
""").df()
def summary_polars(sales: pd.DataFrame) -> pd.DataFrame:
span = pl.col("order_date").max() - pl.col("order_date").min()
return (
pl.from_pandas(sales)
.group_by("customer_id")
.agg(
orders=pl.col("order_id").n_unique(),
revenue=pl.col("revenue").sum().round(2),
active_days=span.dt.total_days(),
)
.sort("customer_id")
.to_pandas()
)
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
start = time.perf_counter()
reference = summary_loop(sales)
loop_seconds = time.perf_counter() - start
start = time.perf_counter()
summary = summary_pandas(sales)
pandas_seconds = time.perf_counter() - start
print("loop at least 10 times slower than pandas:", loop_seconds > 10 * pandas_seconds)
for engine in [summary_pandas, summary_duckdb, summary_polars]:
result = engine(sales)
pd.testing.assert_frame_equal(result, reference, check_dtype=False)
print(f"{engine.__name__}: {len(result)} customers, matches the loop")
top = summary.sort_values(["revenue", "customer_id"], ascending=[False, True])
print(top.iloc[:3].to_string(index=False))
n_top = len(summary) // 10
share = top["revenue"].head(n_top).sum() / summary["revenue"].sum()
print(f"top 10% of buyers ({n_top}) bring {share:.1%} of revenue")
assert len(summary) == 3254
assert abs(summary["revenue"].sum() - 3_596_523.83) < 0.5
Output
loop at least 10 times slower than pandas: True
summary_pandas: 3254 customers, matches the loop
summary_duckdb: 3254 customers, matches the loop
summary_polars: 3254 customers, matches the loop
customer_id orders revenue active_days
C01364 44 16023.65 706
C01766 36 13341.26 719
C01656 24 12785.14 714
top 10% of buyers (325) bring 40.5% of revenue

How it works:

  1. The loop stays as a characterization check: whatever it returns is the behavior to keep. The timing prints a comparison, not the seconds, because durations differ between machines. The loop is more than 10 times slower, because it runs one Python step per row (module 23). Each new version must equal it, row by row (module 25).
  2. pandas named aggregation names the result columns in the call. The assign step computes the span from the two date columns and then drops them, all in one chain.
  3. DuckDB finds the DataFrame sales by its Python name (a replacement scan) and returns a DataFrame with .df(). ORDER BY fixes the order (module 30).
  4. Polars returns UInt32 counts. check_dtype=False compares the values only, and to_pandas() crosses back at the boundary (module 31).
  5. The top 10% of buyers bring 40.5% of revenue. That is a strong reason to look after them.

Which engine: any of the three is fast enough for 20,228 rows. Choose the one the team maintains. pandas fits if the rest of the job is pandas. DuckDB fits if analysts read and change the logic in SQL. Polars fits when the data grows and the job should stream with a lazy query. Do not keep the loop: it is many times slower and harder to read.

P4-09 · Write the code: prepare web traffic for the dashboard

Section titled “P4-09 · Write the code: prepare web traffic for the dashboard”
Core

Write the code: the marketing dashboard shows daily visits from data/web_traffic.csv, a trend line and the “unusual days”. Three problems come first. Five days have no visits (a tracking outage). The team’s outlier rule flags too many days in 2024. And the dashboard needs a smooth trend and the record days.

  1. Choose a fill for the gaps on evidence: hide 100 known days (default_rng(42), not in the first or last week), fill them with forward fill, time interpolation and the value of one week earlier, and compare the mean absolute errors (MAE). Fill the real gaps with the winner and keep an indicator column.
  2. Compare four outlier rules: the IQR rule (above Q3 + 1.5 × IQR) and z > 3, each on the raw visits and on the “detrended” visits: the log of visits divided by the median of the 28 days before. Count the flagged days, how many are campaign days (marketing_spend above 2,000) and how many fall in 2024.
  3. Add a 28-day exponentially weighted trend, and count the record days (a new all-time high) and how many of them are campaign starts.
  4. Plot the visits, the trend and the days of the best rule.
Expected output
gaps: 5
MAE on 100 hidden days: {'ffill': 575, 'interpolate': 422, 'last week': 682}
flagged campaign other in 2024
raw IQR 42 21 21 29
raw z 17 16 1 9
detrended IQR 32 30 2 10
detrended z 25 25 0 8
record days (expanding max): 8, of which campaign starts: 4
Starter
from matplotlib.ticker import FuncFormatter
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")
visits = traffic["visits"]
# TODO: gaps; hide 100 known days; score three fills by MAE; fill the real gaps
# TODO: iqr_flags(s) and z_flags(s); raw and detrended; table of counts
# TODO: EWM trend (span 28); record days with an expanding max; campaign starts
# TODO: chart of visits, trend and flagged days; plt.show()
Hint 1

To score a fill, you need the true values: copy the series, set the hidden days to NaN, fill the copy and compare it with the original on those days. interpolate(method="time") uses the dates, not the row positions.

Hint 2

Visits grow by more than half over three years, so a fixed threshold flags most late days. clean.shift(1).rolling(28).median() is a baseline that uses only earlier days. Flag the ratio to it, not the raw value.

Hint 3

clean.ewm(span=28, adjust=False).mean() weights recent days more than a rolling mean does. A day is a record when it equals clean.expanding().max(). A campaign starts on a campaign day whose previous day is not a campaign day: campaign & ~campaign.shift(1, fill_value=False).

Solution
from matplotlib.ticker import FuncFormatter
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")
visits = traffic["visits"]
print("gaps:", int(visits.isna().sum()))
rng = np.random.default_rng(42)
hide = rng.choice(visits.dropna().index[7:-7], size=100, replace=False)
test = visits.copy()
test[hide] = np.nan
fills = {
"ffill": test.ffill(),
"interpolate": test.interpolate(method="time"),
"last week": test.fillna(test.shift(7)),
}
errors = {
name: round(float((f[hide] - visits[hide]).abs().mean()))
for name, f in fills.items()
}
print("MAE on 100 hidden days:", errors)
clean = visits.interpolate(method="time")
traffic = traffic.assign(visits_clean=clean, visits_filled=visits.isna())
def iqr_flags(s: pd.Series) -> pd.Series:
q1, q3 = s.quantile([0.25, 0.75])
return s > q3 + 1.5 * (q3 - q1)
def z_flags(s: pd.Series) -> pd.Series:
return (s - s.mean()) / s.std() > 3
baseline = clean.shift(1).rolling(28).median() # trailing 4 weeks, today excluded
lift = np.log(clean / baseline)
campaign = traffic["marketing_spend"] > 2000
rules = {
"raw IQR": iqr_flags(clean),
"raw z": z_flags(clean),
"detrended IQR": iqr_flags(lift),
"detrended z": z_flags(lift),
}
table = pd.DataFrame(
{
name: {"flagged": f.sum(), "campaign": (f & campaign).sum(),
"other": (f & ~campaign).sum(), "in 2024": f.loc["2024"].sum()}
for name, f in rules.items()
}
).T
print(table.to_string())
trend = clean.ewm(span=28, adjust=False).mean()
record = clean == clean.expanding().max()
starts = campaign & ~campaign.shift(1, fill_value=False)
print(f"record days (expanding max): {record.sum()}, "
f"of which campaign starts: {(record & starts).sum()}")
fig, ax = plt.subplots(figsize=(9, 4), layout="constrained")
ax.plot(clean.index, clean, linewidth=0.6, color="0.6", label="daily visits")
ax.plot(trend.index, trend, linewidth=2, label="28-day EWM trend")
flagged = rules["detrended z"]
ax.scatter(clean.index[flagged], clean[flagged], color="C3", s=18, zorder=3,
label="detrended z > 3")
ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: f"{v / 1000:.0f}k"))
ax.set(title="Spikes measured against the recent level match the campaigns",
ylabel="Visits per day")
ax.legend(loc="upper left")
assert errors["interpolate"] < errors["ffill"] < errors["last week"]
assert clean.isna().sum() == 0
assert table.loc["detrended z", "other"] == 0
assert table.loc["raw IQR", "in 2024"] > table.loc["detrended IQR", "in 2024"]
plt.show()
Output
gaps: 5
MAE on 100 hidden days: {'ffill': 575, 'interpolate': 422, 'last week': 682}
flagged campaign other in 2024
raw IQR 42 21 21 29
raw z 17 16 1 9
detrended IQR 32 30 2 10
detrended z 25 25 0 8
record days (expanding max): 8, of which campaign starts: 4
Daily visits from 2022 to 2024 rise from about 3k to 6k with seven sharp spikes; the 28-day EWM trend line follows the level, and red dots mark 25 flagged days, all on the seven campaign spikes.
Daily visits, 28-day EWM trend and the days with a detrended z-score above 3.

How it works:

  1. Visits change slowly from day to day, so time interpolation, which uses both neighbors, has the smallest error: 422 visits against 575 for forward fill. One week earlier is worst, because the level moves within a week. The indicator column visits_filled keeps the five estimates visible (module 26).
  2. The raw IQR rule flags 42 days, 21 of them outside campaigns and 29 in 2024: it flags growth, not anomalies. The raw z-score misses many campaign days, because the spikes and the growth inflate the standard deviation.
  3. Against the trailing 28-day median, both rules find the campaigns. The detrended z-score flags 25 days, all of them campaign days. shift(1) keeps the day itself out of its own baseline (module 25).
  4. These spikes are real traffic, not errors: flag them on the dashboard, but do not delete or cap them.
  5. ewm reacts faster than a rolling mean of the same length and has no gap at the start. expanding().max() is the all-time high so far: 8 record days, and 4 of them are campaign starts (module 25).
  6. The chart keeps the daily line light and puts the trend and the flags in front (module 28).

P4-10 · Choose and justify: a test and a chart for four questions

Section titled “P4-10 · Choose and justify: a test and a chart for four questions”
Core

Choose a method and justify it: an analyst brings four questions. For each, choose one statistical test and one chart, and justify both in one sentence each. Then run your choices: print the test result and draw the four charts in one 2 × 2 figure.

  1. Do house prices differ between the 8 neighborhoods of data/houses.csv?
  2. Do churners in data/customers.csv open more support tickets than customers who stay?
  3. Did the treatment in data/ab_test.csv change the time on page?
  4. How are temperature and humidity related in data/sensors.csv (about 8,000 readings)?

Acceptance criteria:

  • A table with four rows: question, data types, test, chart and a one-sentence reason for each choice.
  • Your code prints one line per question with the statistic and the p-value (and the effect where it helps), and draws a 2 × 2 figure.
  • Your reasons mention the property of the data that decides the choice (skewness, number of groups, scale of the variable, sample size, overplotting).
  • Compare your choices with the solution. A different choice is fine if your reason is sound.
Starter
def fmt_p(p: float) -> str:
return "< 0.001" if p < 0.001 else f"= {p:.3f}"
houses = pd.read_csv("data/houses.csv")
customers = pd.read_csv("data/customers.csv")
ab = pd.read_csv("data/ab_test.csv")
sensors = pd.read_csv("data/sensors.csv").dropna(
subset=["temperature_c", "humidity_pct"]
)
# TODO: Q1 to Q4: run the test you chose and print one line each
# TODO: fig, axes = plt.subplots(2, 2, ...); one chart per question; plt.show()
Hint 1

Look at the shape first: is the variable skewed, a small count, a 0/1 flag or a continuous measure? How many groups are there? How large is each group?

Hint 2

With 8,000 points, a scatter plot turns into a solid blob. A hexbin or a 2D histogram shows where the points really are. For a 0/1 outcome by a small count, a bar chart of the rate per count shows the dose–response.

Solution
QuestionDataTestChart
1. Price by neighborhoodskewed number, 8 groupsKruskal–Wallis: it compares many groups by ranks, so the skew and the outliers do not dominatebox plots on a log axis, sorted by median: they show the center, the spread and the outliers of every group
2. Tickets by churnsmall count 0–9, two groupsMann–Whitney U: the count is ordinal and skewed, not normal, and the test handles the many tiesbar chart of the churn rate per ticket count, with 5+ merged: it shows that the rate rises with each ticket
3. Time on page by groupcontinuous, two large groupsWelch t-test: with 5,000 users per group the CLT makes the means normal, and Welch does not assume equal variancesoverlaid step histograms with density: they compare the whole distributions, not only the means
4. Temperature and humiditytwo numbers, 8,013 pointsSpearman correlation: it measures a monotonic link and resists the temperature spikeshexbin with a log color scale: it avoids overplotting
def fmt_p(p: float) -> str:
return "< 0.001" if p < 0.001 else f"= {p:.3f}"
houses = pd.read_csv("data/houses.csv")
customers = pd.read_csv("data/customers.csv")
ab = pd.read_csv("data/ab_test.csv")
sensors = pd.read_csv("data/sensors.csv").dropna(
subset=["temperature_c", "humidity_pct"]
)
# Q1: price (skewed number) across 8 neighborhoods
order = houses.groupby("neighborhood")["price"].median().sort_values().index
groups = [houses.loc[houses["neighborhood"] == n, "price"] for n in order]
kw = stats.kruskal(*groups)
print(f"Q1 skew {houses['price'].skew():.2f}; Kruskal-Wallis H = {kw.statistic:.0f}, "
f"p {fmt_p(kw.pvalue)}")
# Q2: support tickets (small count) for churners vs stayers
churned = customers["churned"] == 1
tickets = customers["support_tickets"]
mw = stats.mannwhitneyu(tickets[churned], tickets[~churned])
cles = mw.statistic / (churned.sum() * (~churned).sum()) # ties count 1/2
diff = np.subtract.outer(tickets[churned].to_numpy(), tickets[~churned].to_numpy())
print(f"Q2 Mann-Whitney p {fmt_p(mw.pvalue)}, U/(n1*n2) = {cles:.3f}: "
f"P(more) {(diff > 0).mean():.3f} + P(tie)/2 {(diff == 0).mean() / 2:.3f}")
# Q3: time on page (continuous, large groups) for treatment vs control
treat = ab.loc[ab["group"] == "treatment", "time_on_page_s"]
ctrl = ab.loc[ab["group"] == "control", "time_on_page_s"]
welch = stats.ttest_ind(treat, ctrl, equal_var=False)
print(f"Q3 Levene p {fmt_p(stats.levene(treat, ctrl).pvalue)}; Welch t = "
f"{welch.statistic:.2f}, p {fmt_p(welch.pvalue)}, "
f"diff {treat.mean() - ctrl.mean():.1f} s")
# Q4: temperature and humidity (two numbers, 8,000 points)
rho = stats.spearmanr(sensors["temperature_c"], sensors["humidity_pct"])
r = stats.pearsonr(sensors["temperature_c"], sensors["humidity_pct"])
print(f"Q4 Spearman {rho.statistic:.2f}, Pearson {r.statistic:.2f}, n = {len(sensors)}")
fig, axes = plt.subplots(2, 2, figsize=(11, 8), layout="constrained")
axes[0, 0].boxplot([g / 1000 for g in groups], tick_labels=list(order),
orientation="horizontal")
axes[0, 0].set(xscale="log", xlabel="Price (thousand USD, log scale)",
title="Q1: box plots per neighborhood")
axes[0, 0].set_xticks([200, 500, 1000, 2000], labels=["200", "500", "1,000", "2,000"])
axes[0, 0].minorticks_off()
banded = tickets.clip(upper=5)
rate = customers.groupby(banded)["churned"].mean()
axes[0, 1].bar(["0", "1", "2", "3", "4", "5+"], rate.to_numpy())
axes[0, 1].set(xlabel="Support tickets", ylabel="Churn rate",
title="Q2: churn rate per ticket count")
bins = np.linspace(0, 300, 41)
axes[1, 0].hist([ctrl, treat], bins=bins, density=True, histtype="step",
label=["control", "treatment"])
axes[1, 0].set(xlabel="Time on page (s)", ylabel="Density",
title="Q3: overlaid histograms")
axes[1, 0].legend()
hb = axes[1, 1].hexbin(sensors["temperature_c"], sensors["humidity_pct"],
gridsize=40, bins="log", cmap="viridis")
fig.colorbar(hb, ax=axes[1, 1], label="Readings (log)")
axes[1, 1].set(xlabel="Temperature (°C)", ylabel="Humidity (%)",
title="Q4: hexbin, not 8,000 dots")
assert kw.pvalue < 0.001 and mw.pvalue < 0.001 and welch.pvalue < 0.001
assert rho.statistic < -0.5
assert np.isclose(cles, (diff > 0).mean() + (diff == 0).mean() / 2)
assert rate.index.tolist() == [0, 1, 2, 3, 4, 5]
plt.show()
Output
Q1 skew 2.67; Kruskal-Wallis H = 1784, p < 0.001
Q2 Mann-Whitney p < 0.001, U/(n1*n2) = 0.625: P(more) 0.508 + P(tie)/2 0.117
Q3 Levene p = 0.184; Welch t = 8.48, p < 0.001, diff 9.0 s
Q4 Spearman -0.57, Pearson -0.55, n = 8013
Four panels: box plots of house prices per neighborhood from Cedar Park to Lakeview; churn rate rising from 0.13 at 0 tickets to 0.60 at 5 or more; two almost overlapping right-skewed histograms of time on page; a hexbin showing humidity falling as temperature rises, with a few isolated spike readings at 30–45 °C.
One chart per question, chosen for the type of data.

How it works:

  1. Q1: an ANOVA on log price would also be sound (P4-12 runs an ANOVA on log revenue), because log price is close to normal. Kruskal–Wallis needs no transform. With H = 1,784 on 7 degrees of freedom, the medians clearly differ (module 29).
  2. Q2: with ties, U / (n1 * n2) is the common-language effect size P(more) + ½ P(tie), here 0.625. Broadcasting with np.subtract.outer compares all 3.9 million pairs: a churner has more tickets in 50.8% of the pairs, the same number in 23.3% and fewer in the rest. The chart shows the dose–response that the test only summarizes. Merging 5 to 9 tickets avoids bars built on 1 customer (module 27).
  3. Q3: Levene’s test (p = 0.184) does not show unequal variances, but Welch costs nothing when they are equal. The treatment adds 9.0 seconds on average.
  4. Q4: Spearman (−0.57) and Pearson (−0.55) agree here, but the hexbin shows the spike readings far to the right. A single scatter plot of 8,013 points would hide the dense center (module 28).

P4-11 · Interpret a result: do better-rated products sell more?

Section titled “P4-11 · Interpret a result: do better-rated products sell more?”
Core

Interpret a result: the merchandising team wants to promote the best-rated products, “because they are our best sellers”. Check the claim with DuckDB on the CSV files: per product, the mean rating and the number of reviews from data/reviews.csv, the units sold from data/sales.csv, and the days on sale in 2023–2024 (four products launched inside the period). Compute units per day. Compare the Spearman correlation of the rating with raw units and with units per day, and the correlation of price with units per day. Fit an OLS of log units per day on the rating and log price. Draw an interactive scatter plot with Plotly Express, with the product name in the tooltip. Write the conclusion as claim → evidence → caveat.

Expected output
30 products, 3000 reviews, 29533 units
product mean_rating units_per_day
Adjustable Dumbbells 4.28 0.84
Harbor Lane Mysteries 4.21 1.85
Chef's Knife Set 4.15 1.23
Spearman rating vs units: -0.26 (p = 0.158)
Spearman rating vs units_per_day: -0.42 (p = 0.020)
Spearman price vs units_per_day: -0.62 (p = 0.0003)
OLS rating coefficient -0.44 [-0.81, -0.07] on log units/day, holding log price fixed
Starter
import plotly.express as px
products = duckdb.sql("""
WITH ratings AS (...),
units AS (...)
SELECT ...
FROM 'data/products.csv' AS p
...
""").df()
# TODO: units_per_day; totals; the 3 best-rated products
# TODO: Spearman: rating vs units, rating vs units_per_day, price vs units_per_day
# TODO: OLS of log units per day on rating and log price
# TODO: px.scatter with hover_name="product"; fig.show()
Hint 1

A product launched in 2024 had less time to sell. greatest(p.launch_date, DATE '2023-01-01') gives the first day on sale in the period, and date_diff('day', start, DATE '2024-12-31') + 1 counts the days, both days included.

Hint 2

Price is a likely confounder: cheap products sell more units, and price may be linked to the rating. Put np.log(unit_price) in the OLS formula to compare products at the same price.

Solution
import plotly.express as px
products = duckdb.sql("""
WITH ratings AS (
SELECT product_id, AVG(rating) AS mean_rating, COUNT(*) AS reviews
FROM 'data/reviews.csv'
GROUP BY product_id
),
units AS (
SELECT product_id, SUM(quantity)::INTEGER AS units
FROM 'data/sales.csv'
GROUP BY product_id
)
SELECT p.product_id, p.product, p.category, p.unit_price, r.mean_rating,
r.reviews, u.units,
date_diff('day', greatest(p.launch_date, DATE '2023-01-01'),
DATE '2024-12-31') + 1 AS days_on_sale
FROM 'data/products.csv' AS p
JOIN ratings AS r USING (product_id)
JOIN units AS u USING (product_id)
ORDER BY p.product_id
""").df()
products["units_per_day"] = products["units"] / products["days_on_sale"]
print(f"{len(products)} products, {products['reviews'].sum()} reviews, "
f"{products['units'].sum()} units")
print(products.nlargest(3, "mean_rating")[["product", "mean_rating", "units_per_day"]]
.round(2).to_string(index=False))
for y in ["units", "units_per_day"]:
rho = stats.spearmanr(products["mean_rating"], products[y])
print(f"Spearman rating vs {y}: {rho.statistic:+.2f} (p = {rho.pvalue:.3f})")
rho_price = stats.spearmanr(products["unit_price"], products["units_per_day"])
print(f"Spearman price vs units_per_day: {rho_price.statistic:+.2f} "
f"(p = {rho_price.pvalue:.4f})")
fit = smf.ols(
"np.log(units_per_day) ~ mean_rating + np.log(unit_price)", data=products
).fit()
low, high = fit.conf_int().loc["mean_rating"]
print(f"OLS rating coefficient {fit.params['mean_rating']:+.2f} "
f"[{low:+.2f}, {high:+.2f}] on log units/day, holding log price fixed")
fig = px.scatter(
products,
x="mean_rating",
y="units_per_day",
color="category",
size="unit_price",
hover_name="product",
hover_data={"reviews": True, "days_on_sale": True},
log_y=True,
title="Better-rated products do not sell more units per day",
labels={"mean_rating": "Mean review rating", "units_per_day": "Units per day"},
)
assert products["reviews"].sum() == 3000 and products["units"].sum() == 29533
assert stats.spearmanr(products["mean_rating"], products["units_per_day"])[0] < 0
fig.show()
Output
30 products, 3000 reviews, 29533 units
product mean_rating units_per_day
Adjustable Dumbbells 4.28 0.84
Harbor Lane Mysteries 4.21 1.85
Chef's Knife Set 4.15 1.23
Spearman rating vs units: -0.26 (p = 0.158)
Spearman rating vs units_per_day: -0.42 (p = 0.020)
Spearman price vs units_per_day: -0.62 (p = 0.0003)
OLS rating coefficient -0.44 [-0.81, -0.07] on log units/day, holding log price fixed
Mean review rating against units sold per day for 30 products, colored by category, interactive · Open the interactive chart in a new tab

How it works:

  1. Each CTE aggregates one table to one row per product before the join, so the join cannot fan out. The totals match the data dictionary: 3,000 reviews and 29,533 units (module 30).
  2. Raw units favor products that were on sale longer. Units per day remove that bias. The correlation with the rating moves from −0.26 to −0.42 (module 27).
  3. Price is the strongest driver: Spearman −0.62 between price and units per day. With log price in the model, the rating coefficient is still negative, −0.44, with a CI that excludes zero (module 29).
  4. The Plotly tooltip shows which product sits where, for example Adjustable Dumbbells: the best rating but under one unit per day (module 28).

Conclusion:

  • Claim: better-rated products do not sell more. If anything, they sell fewer units per day.
  • Evidence: Spearman −0.42 (p = 0.020) between the rating and units per day over 30 products, and −0.44 per rating point on log units per day at the same price.
  • Caveat: 30 products is a small sample, and this was one of several comparisons, so the negative sign may be chance. The data is observational: a promotion test is the only way to learn whether promoting by rating moves sales. Do not use “best sellers” as the reason for the campaign.

P4-12 · Interpret a result: do tablet buyers spend more?

Section titled “P4-12 · Interpret a result: do tablet buyers spend more?”
Core

Interpret a result: a product manager looks at data/ab_test.csv and sees that tablet buyers spend 44.18 USD on average and desktop buyers 40.05 USD. She wants premium offers for tablet users. Check whether the device matters for the spend of buyers (converted 1).

  1. Summarize revenue per device, and the skewness of revenue and of log revenue.
  2. Fit a normal distribution to log revenue with stats.norm.fit. Compare the model with the data on two questions: the share of buyers above 100 USD (sf) and the 95th percentile (ppf).
  3. Show the central limit theorem (CLT) on this skewed data: draw 10,000 samples of 50 buyers (default_rng(42)), and compare the skewness and the standard deviation of their means with the formula s/ns/\sqrt{n}.
  4. Compare log revenue across the three devices with Levene’s test, a one-way ANOVA and Kruskal–Wallis, and compute the effect size eta squared (η2\eta^2, the share of the variance that the device explains).
  5. Draw the revenue distribution per device in one Seaborn figure with a panel per device and a log x axis.
Expected output
size mean median
device
desktop 454 40.05 32.25
mobile 516 43.97 35.84
tablet 119 44.18 37.99
skew: revenue 2.21, log revenue -0.01
share above 100 USD: model 0.049, data 0.047
95th percentile: model 99.3, data 98.6
means of 50 buyers: skew 0.32, SD 4.18 (formula 4.20)
Levene p = 0.110; ANOVA F = 3.35, p = 0.036; Kruskal p = 0.052; eta² = 0.006
Starter
ab = pd.read_csv("data/ab_test.csv")
buyers = ... # TODO: converted buyers with a log_revenue column
# TODO: summary per device; skewness of revenue and log revenue
# TODO: stats.norm.fit on log revenue; sf at log(100); ppf at 0.95
# TODO: CLT: 10,000 means of 50 buyers; skew and SD against s / sqrt(50)
# TODO: Levene, ANOVA and Kruskal on log revenue; eta squared
# TODO: sns.displot with col="device" and log_scale=True; plt.show()
Hint 1

If log revenue is normal, stats.norm.sf(np.log(100), mu, sigma) is the share of buyers above 100 USD, and np.exp(stats.norm.ppf(0.95, mu, sigma)) is the 95th percentile in USD.

Hint 2

Eta squared is the sum of squares between the groups divided by the total sum of squares: η2=∑gng(xˉg−xˉ)2/∑i(xi−xˉ)2\eta^2 = \sum_g n_g(\bar{x}_g - \bar{x})^2 / \sum_i (x_i - \bar{x})^2. A value of 0.01 is usually called small.

Solution
ab = pd.read_csv("data/ab_test.csv")
buyers = ab[ab["converted"] == 1].assign(log_revenue=lambda d: np.log(d["revenue"]))
summary = buyers.groupby("device")["revenue"].agg(["size", "mean", "median"])
print(summary.round(2).to_string())
print(f"skew: revenue {buyers['revenue'].skew():.2f}, "
f"log revenue {buyers['log_revenue'].skew():.2f}")
mu, sigma = stats.norm.fit(buyers["log_revenue"])
model_share = stats.norm.sf(np.log(100), mu, sigma)
model_p95 = np.exp(stats.norm.ppf(0.95, mu, sigma))
print(f"share above 100 USD: model {model_share:.3f}, data "
f"{(buyers['revenue'] > 100).mean():.3f}")
print(f"95th percentile: model {model_p95:.1f}, data "
f"{buyers['revenue'].quantile(0.95):.1f}")
rng = np.random.default_rng(42)
means = rng.choice(buyers["revenue"].to_numpy(), size=(10_000, 50)).mean(axis=1)
se_formula = buyers["revenue"].std() / np.sqrt(50)
print(f"means of 50 buyers: skew {stats.skew(means):.2f}, "
f"SD {means.std(ddof=1):.2f} (formula {se_formula:.2f})")
groups = [g.to_numpy() for _, g in buyers.groupby("device")["log_revenue"]]
levene = stats.levene(*groups)
anova = stats.f_oneway(*groups)
kruskal = stats.kruskal(*groups)
grand = buyers["log_revenue"].mean()
ss_between = sum(g.size * (g.mean() - grand) ** 2 for g in groups)
eta_sq = ss_between / ((buyers["log_revenue"] - grand) ** 2).sum()
print(f"Levene p = {levene.pvalue:.3f}; ANOVA F = {anova.statistic:.2f}, "
f"p = {anova.pvalue:.3f}; Kruskal p = {kruskal.pvalue:.3f}; eta² = {eta_sq:.3f}")
grid = sns.displot(
data=buyers, x="revenue", col="device", col_order=["desktop", "mobile", "tablet"],
log_scale=True, stat="density", common_norm=False, kde=True, height=3, aspect=1.1,
)
grid.set_axis_labels("Revenue per buyer (USD, log scale)", "Density")
for ax in grid.axes.flat:
ax.set_xticks([10, 30, 100, 300], labels=["10", "30", "100", "300"])
ax.minorticks_off()
grid.figure.suptitle("Buyers spend about the same on every device")
grid.figure.subplots_adjust(top=0.8)
assert summary["size"].sum() == 1089
assert abs(model_share - (buyers["revenue"] > 100).mean()) < 0.01
assert anova.pvalue < 0.05 < kruskal.pvalue and eta_sq < 0.01
plt.show()
Output
size mean median
device
desktop 454 40.05 32.25
mobile 516 43.97 35.84
tablet 119 44.18 37.99
skew: revenue 2.21, log revenue -0.01
share above 100 USD: model 0.049, data 0.047
95th percentile: model 99.3, data 98.6
means of 50 buyers: skew 0.32, SD 4.18 (formula 4.20)
Levene p = 0.110; ANOVA F = 3.35, p = 0.036; Kruskal p = 0.052; eta² = 0.006
Three histograms with density curves of revenue per buyer on a log axis, for desktop, mobile and tablet; all three are bell-shaped around 30 to 40 USD with the same spread.
Revenue per buyer by device, log scale.

How it works:

  1. Revenue is right-skewed (2.21). Log revenue has a skewness of −0.01, so a log-normal model is plausible, as the data dictionary says (module 27).
  2. The fitted normal on the log scale predicts 4.9% of buyers above 100 USD; the data has 4.7%. The predicted 95th percentile is 99.3 USD against 98.6 USD. The model is good enough for planning questions such as “how many big baskets will we see?” (module 29).
  3. The CLT in action: single buyers are skewed, but the means of 50 buyers have a skewness of only 0.32, and their standard deviation (4.18) matches the standard error s/50s/\sqrt{50} (4.20). This is why a t-interval for mean spend works here.
  4. Levene’s test does not show unequal variances (p = 0.110), so the ANOVA is acceptable. It gives p = 0.036, but Kruskal–Wallis gives p = 0.052: the result sits on the 0.05 line. Eta squared is 0.006: the device explains 0.6% of the variance in log spend.
  5. The Seaborn figure-level function displot builds one panel per device (a FacetGrid). The three shapes look almost the same (module 28).

For the product manager: “The device explains less than 1% of how much a buyer spends. The difference is borderline significant (ANOVA p = 0.036, Kruskal–Wallis p = 0.052), and the main difference is that desktop buyers spend a bit less, not that tablet buyers spend more. Tablet has only 119 buyers. Premium offers for tablet users are not supported by this data.”

P4-13 · Write the code: a regional category-mix pack

Section titled “P4-13 · Write the code: a regional category-mix pack”
Core

Write the code: the four regional managers want to see how the category mix of their region changed from 2023 to 2024. Load data/sales.csv with the text columns as category dtype and the quantity downcast, and report the memory before and after. Build a revenue cube by region, category and year (a Series with a three-level MultiIndex). Reshape it to one column per year, add the growth and each category’s share of its region’s 2024 revenue, and print the growth as a category × region table. Print the Electronics share per region with xs. Keep only the categories that grew more than 20% in every region with a group filter. Then melt the two year columns to long format, rebuild them with pivot_table, and check stack against the cube. Draw one bar panel per region with Seaborn.

Expected output
memory: 3.45 MB -> 1.38 MB (40%)
cube: 48 rows, levels ['region', 'category', 'year']
region East North South West
category
Beauty 32.2 32.2 46.2 16.2
Books 20.3 21.2 9.7 13.8
Clothing 16.7 9.3 19.6 30.9
Electronics 10.9 5.5 8.1 8.1
Home 55.8 50.2 34.7 38.1
Sports 23.3 15.2 25.4 26.2
Electronics share of 2024 revenue: {'East': 0.506, 'North': 0.467, 'South': 0.479, 'West': 0.47}
growth above 20% in every region: ['Home']
long: (48, 4) | melt round trip: True | stack equals cube: True
Starter
from matplotlib.ticker import FuncFormatter
text_cols = ["store_id", "region", "channel", "product_id", "product", "category"]
raw = pd.read_csv("data/sales.csv")
# TODO: read again with category dtypes and downcast quantity; memory before/after
# TODO: cube = revenue by region, category and year (observed=True)
# TODO: unstack the year; growth_pct; share_2024 with groupby(level=...).transform
# TODO: growth as category x region; Electronics share with xs; groupby filter
# TODO: melt to long; pivot_table back; stack check; sns.catplot; plt.show()
Hint 1

dtype=dict.fromkeys(text_cols, "category") sets the dtype at load time. Measure with memory_usage(deep=True).sum(): without deep=True, pandas does not count the text.

Hint 2

cube.unstack("year") moves the year level to the columns. wide.groupby(level="region")[2024].transform("sum") puts each region’s total next to every row of that region. wide["growth_pct"].unstack("region") turns the regions into columns.

Hint 3

groupby(level="category").filter(lambda g: ...) keeps or drops all rows of a category at once. Seaborn wants long data: one row per region, category and year. That is what melt makes.

Solution
from matplotlib.ticker import FuncFormatter
text_cols = ["store_id", "region", "channel", "product_id", "product", "category"]
raw = pd.read_csv("data/sales.csv")
sales = pd.read_csv(
"data/sales.csv",
parse_dates=["order_date"],
dtype=dict.fromkeys(text_cols, "category"),
)
sales["quantity"] = pd.to_numeric(sales["quantity"], downcast="integer")
before, after = raw.memory_usage(deep=True).sum(), sales.memory_usage(deep=True).sum()
print(f"memory: {before / 1e6:.2f} MB -> {after / 1e6:.2f} MB ({after / before:.0%})")
cube = sales.groupby(
["region", "category", sales["order_date"].dt.year.rename("year")], observed=True
)["revenue"].sum()
print("cube:", len(cube), "rows, levels", list(cube.index.names))
wide = cube.unstack("year")
wide["growth_pct"] = (wide[2024] / wide[2023] - 1) * 100
wide["share_2024"] = wide[2024] / wide.groupby(level="region")[2024].transform("sum")
print(wide["growth_pct"].unstack("region").round(1).to_string())
electronics = wide.xs("Electronics", level="category")["share_2024"]
print("Electronics share of 2024 revenue:", electronics.round(3).to_dict())
fast = wide.groupby(level="category").filter(lambda g: (g["growth_pct"] > 20).all())
print("growth above 20% in every region:",
fast.index.get_level_values("category").unique().tolist())
long = (
wide[[2023, 2024]]
.reset_index()
.melt(id_vars=["region", "category"], var_name="year", value_name="revenue")
)
back = long.pivot_table(index=["region", "category"], columns="year", values="revenue")
stacked = wide[[2023, 2024]].stack() # back to one value per (region, category, year)
print("long:", long.shape, "| melt round trip:", np.allclose(back, wide[[2023, 2024]]),
"| stack equals cube:", np.allclose(stacked.sort_index(), cube.sort_index()))
grid = sns.catplot(
data=long, kind="bar", x="revenue", y="category", hue="year", col="region",
col_wrap=2, height=2.8, aspect=1.4, palette="colorblind",
order=wide.groupby(level="category")[2024].sum().sort_values().index[::-1],
)
grid.set_axis_labels("Revenue (thousand USD)", "")
for ax in grid.axes.flat:
ax.xaxis.set_major_formatter(FuncFormatter(lambda v, _: f"{v / 1000:.0f}"))
grid.figure.suptitle("Only Home grew more than 20% in every region")
grid.figure.subplots_adjust(top=0.9)
assert after < 0.5 * before
assert len(cube) == 48 and long.shape == (48, 4)
assert np.allclose(wide.groupby(level="region")["share_2024"].sum(), 1)
plt.show()
Output
memory: 3.45 MB -> 1.38 MB (40%)
cube: 48 rows, levels ['region', 'category', 'year']
region East North South West
category
Beauty 32.2 32.2 46.2 16.2
Books 20.3 21.2 9.7 13.8
Clothing 16.7 9.3 19.6 30.9
Electronics 10.9 5.5 8.1 8.1
Home 55.8 50.2 34.7 38.1
Sports 23.3 15.2 25.4 26.2
Electronics share of 2024 revenue: {'East': 0.506, 'North': 0.467, 'South': 0.479, 'West': 0.47}
growth above 20% in every region: ['Home']
long: (48, 4) | melt round trip: True | stack equals cube: True
Four bar panels, one per region, with 2023 and 2024 revenue per category: Electronics leads everywhere at about 200 to 275 thousand USD, and Home shows the largest jump in every region.
Revenue by category, region and year.

How it works:

  1. The category dtype stores each distinct text once and keeps small integer codes per row. With the downcast quantity, the table needs 40% of its memory (module 25).
  2. Grouping by three keys gives a Series with a three-level MultiIndex: 4 regions × 6 categories × 2 years = 48 rows. observed=True keeps only the combinations that exist.
  3. unstack("year") makes the table wide. transform("sum") returns the region total on every row, so the share is one division. Within each region, the shares add up to 1.
  4. xs("Electronics", level="category") selects one value of an inner level. Electronics still brings 47% to 51% of each region’s 2024 revenue, even though it grew least (5.5% to 10.9%).
  5. Beauty grew most in the South (46.2%), but Home is the only category above 20% in all four regions. filter makes that rule explicit.
  6. melt and pivot_table are inverse operations here, as are stack and unstack. The checks prove that no value was lost. The long table feeds sns.catplot, which makes one panel per region (module 28).

P4-14 · Fix the method: store growth without the seasonal trap

Section titled “P4-14 · Fix the method: store growth without the seasonal trap”
Challenge

The operations director asks for the annual growth rate of each store, ranked within its region. A colleague fitted a straight line to the log of monthly revenue and reports growth of 28% to 55%. That is far above the 18.6% growth of the whole shop. Fix the method: find the error and correct it.

Use Polars to build a month × store revenue matrix (24 × 11; leave out S12, which opened in June 2023). Fit both models to all 11 stores at once with np.linalg.lstsq: the naive trend line, and a trend plus 12 month-of-year dummies. Compare their root-mean-square error (RMSE) on log revenue. Convert each slope to growth per year, add the plain year-over-year (YoY) growth, join the store cities and regions, and rank the stores within each region with a window expression. Check how well the seasonal growth agrees with YoY growth. Split the 24 months into the two years with np.split for the YoY growth. Draw one store’s fit and the naive and seasonal growth of all stores, ordered with a fancy index.

Expected output
matrix: (24, 11) | missing: 0
{'naive': 0.354, 'seasonal': 0.201}
┌──────────┬───────────┬──────────────┬─────────┬───────────────┬────────┬────────────────┐
│ store_id ┆ naive_pct ┆ seasonal_pct ┆ yoy_pct ┆ city ┆ region ┆ rank_in_region │
╞══════════╪═══════════╪══════════════╪═════════╪═══════════════╪════════╪════════════════╡
│ S07 ┆ 45.2 ┆ 22.4 ┆ 29.1 ┆ New York ┆ East ┆ 1 │
│ S09 ┆ 42.5 ┆ 15.6 ┆ 18.1 ┆ Philadelphia ┆ East ┆ 2 │
│ S08 ┆ 28.1 ┆ 11.7 ┆ 12.1 ┆ Boston ┆ East ┆ 3 │
│ S03 ┆ 49.1 ┆ 21.2 ┆ 17.6 ┆ Detroit ┆ North ┆ 1 │
│ S01 ┆ 47.2 ┆ 20.8 ┆ 19.0 ┆ Chicago ┆ North ┆ 2 │
│ S02 ┆ 54.5 ┆ 15.3 ┆ 11.6 ┆ Minneapolis ┆ North ┆ 3 │
│ S06 ┆ 46.6 ┆ 23.0 ┆ 31.6 ┆ Miami ┆ South ┆ 1 │
│ S05 ┆ 32.8 ┆ 16.1 ┆ 14.3 ┆ Atlanta ┆ South ┆ 2 │
│ S04 ┆ 36.2 ┆ 11.4 ┆ 14.0 ┆ Houston ┆ South ┆ 3 │
│ S10 ┆ 28.4 ┆ 17.6 ┆ 13.3 ┆ Seattle ┆ West ┆ 1 │
│ S11 ┆ 29.1 ┆ 10.6 ┆ 10.6 ┆ San Francisco ┆ West ┆ 2 │
└──────────┴───────────┴──────────────┴─────────┴───────────────┴────────┴────────────────┘
Spearman seasonal vs year-over-year growth: 0.84
Starter
sales = pl.read_csv("data/sales.csv", try_parse_dates=True)
stores = pl.read_csv("data/stores.csv")
# TODO: month x store revenue (no S12), sorted by month; log values as NumPy
# TODO: naive design [1, t] and seasonal design [12 month dummies, t]; lstsq both
# TODO: RMSE of both; growth per year = exp(12 * slope) - 1; YoY with np.split
# TODO: join stores, round, rank within region with .over("region"), print
# TODO: Spearman between seasonal and YoY growth; two-panel chart; plt.show()
Hint 1

The series starts in the January–February dip and ends in the November–December peak. A straight line through it climbs too steeply. Month dummies give each calendar month its own level, so the slope only measures the change from one year to the next.

Hint 2

np.tile(np.eye(12), (2, 1)) stacks two 12 × 12 identity matrices: one dummy column per calendar month for 24 months. Add t as the 13th column. Do not add a column of ones: it would equal the sum of the dummies.

Hint 3

In Polars, pl.col("seasonal_pct").rank(descending=True).over("region") ranks within each region. pl.selectors.ends_with("_pct").round(1) rounds all the growth columns at once.

Solution
sales = pl.read_csv("data/sales.csv", try_parse_dates=True)
stores = pl.read_csv("data/stores.csv")
wide = (
sales.filter(pl.col("store_id") != "S12")
.group_by(pl.col("order_date").dt.truncate("1mo").alias("month"), "store_id")
.agg(pl.col("revenue").sum())
.pivot(on="store_id", index="month", values="revenue", sort_columns=True)
.sort("month")
)
ids = wide.columns[1:]
log_rev = np.log(wide.drop("month").to_numpy()) # 24 months x 11 stores
print("matrix:", log_rev.shape, "| missing:", int(np.isnan(log_rev).sum()))
t = np.arange(24)
naive_X = np.column_stack([np.ones(24), t])
season_X = np.column_stack([np.tile(np.eye(12), (2, 1)), t]) # 12 month dummies
naive, *_ = np.linalg.lstsq(naive_X, log_rev, rcond=None)
season, *_ = np.linalg.lstsq(season_X, log_rev, rcond=None)
rmse = {
"naive": np.sqrt(((log_rev - naive_X @ naive) ** 2).mean()),
"seasonal": np.sqrt(((log_rev - season_X @ season) ** 2).mean()),
}
print({k: round(float(v), 3) for k, v in rmse.items()})
totals = wide.drop("month").to_numpy()
year_2023, year_2024 = np.split(totals, 2) # two 12 x 11 blocks
yoy = year_2024.sum(axis=0) / year_2023.sum(axis=0) - 1
growth = pl.DataFrame(
{
"store_id": ids,
"naive_pct": (np.exp(12 * naive[1]) - 1) * 100,
"seasonal_pct": (np.exp(12 * season[12]) - 1) * 100,
"yoy_pct": yoy * 100,
}
)
table = (
growth.join(stores.select("store_id", "city", "region"), on="store_id",
validate="1:1")
.with_columns(
pl.selectors.ends_with("_pct").round(1),
rank_in_region=pl.col("seasonal_pct")
.rank(descending=True)
.over("region")
.cast(pl.Int8),
)
.sort("region", "rank_in_region")
)
with pl.Config(tbl_rows=12, tbl_hide_dataframe_shape=True,
tbl_hide_column_data_types=True):
print(table)
rho = stats.spearmanr(growth["seasonal_pct"], growth["yoy_pct"]).statistic
print(f"Spearman seasonal vs year-over-year growth: {rho:.2f}")
fig, (left, right) = plt.subplots(1, 2, figsize=(11, 4), layout="constrained")
j = ids.index("S06")
months = wide["month"].to_numpy()
left.plot(months, np.exp(log_rev[:, j]) / 1000, marker="o", label="actual")
left.plot(months, np.exp(naive_X @ naive[:, j]) / 1000, "--", label="trend only")
left.plot(months, np.exp(season_X @ season[:, j]) / 1000, ":", label="trend + month")
left.set(title="S06 Miami: a trend-only line chases the year-end peak",
ylabel="Monthly revenue (thousand USD)")
left.legend()
left.tick_params(axis="x", rotation=45)
order = np.argsort(growth["seasonal_pct"].to_numpy()) # fancy index, low to high
y = np.arange(len(order))
right.barh(y - 0.2, growth["naive_pct"].to_numpy()[order], height=0.4,
label="trend only")
right.barh(y + 0.2, growth["seasonal_pct"].to_numpy()[order], height=0.4,
label="trend + month")
right.set_yticks(y, np.array(ids)[order])
right.set(title="Annual growth per store", xlabel="Growth per year (%)")
right.legend(loc="lower right")
assert table.height == 11
assert rmse["seasonal"] < rmse["naive"]
assert (growth["naive_pct"] > growth["seasonal_pct"]).all()
assert rho > 0.7
plt.show()
Output
matrix: (24, 11) | missing: 0
{'naive': 0.354, 'seasonal': 0.201}
┌──────────┬───────────┬──────────────┬─────────┬───────────────┬────────┬────────────────┐
│ store_id ┆ naive_pct ┆ seasonal_pct ┆ yoy_pct ┆ city ┆ region ┆ rank_in_region │
╞══════════╪═══════════╪══════════════╪═════════╪═══════════════╪════════╪════════════════╡
│ S07 ┆ 45.2 ┆ 22.4 ┆ 29.1 ┆ New York ┆ East ┆ 1 │
│ S09 ┆ 42.5 ┆ 15.6 ┆ 18.1 ┆ Philadelphia ┆ East ┆ 2 │
│ S08 ┆ 28.1 ┆ 11.7 ┆ 12.1 ┆ Boston ┆ East ┆ 3 │
│ S03 ┆ 49.1 ┆ 21.2 ┆ 17.6 ┆ Detroit ┆ North ┆ 1 │
│ S01 ┆ 47.2 ┆ 20.8 ┆ 19.0 ┆ Chicago ┆ North ┆ 2 │
│ S02 ┆ 54.5 ┆ 15.3 ┆ 11.6 ┆ Minneapolis ┆ North ┆ 3 │
│ S06 ┆ 46.6 ┆ 23.0 ┆ 31.6 ┆ Miami ┆ South ┆ 1 │
│ S05 ┆ 32.8 ┆ 16.1 ┆ 14.3 ┆ Atlanta ┆ South ┆ 2 │
│ S04 ┆ 36.2 ┆ 11.4 ┆ 14.0 ┆ Houston ┆ South ┆ 3 │
│ S10 ┆ 28.4 ┆ 17.6 ┆ 13.3 ┆ Seattle ┆ West ┆ 1 │
│ S11 ┆ 29.1 ┆ 10.6 ┆ 10.6 ┆ San Francisco ┆ West ┆ 2 │
└──────────┴───────────┴──────────────┴─────────┴───────────────┴────────┴────────────────┘
Spearman seasonal vs year-over-year growth: 0.84
Left: monthly revenue of S06 Miami with a straight trend line that climbs steeply and a seasonal fit that follows the peaks. Right: horizontal bars per store where the trend-only growth of 28 to 55% is about double the seasonal growth of 11 to 23%.
Trend-only growth against trend plus month-of-year growth, 11 stores.

How it works:

  1. dt.truncate("1mo") maps each date to its month. pivot with sort_columns=True gives one column per store in a fixed order (module 31).
  2. lstsq accepts a 24 × 11 matrix of targets, so one call fits 11 models. The seasonal design has 13 columns and full rank. np.split(totals, 2) cuts the matrix into the two years, and argsort gives an index array that reorders the bars (fancy indexing) (module 23).
  3. The month dummies cut the RMSE from 0.354 to 0.201 on the log scale. In the naive model, the season was in the residuals and tilted the slope.
  4. With 24 months, the seasonal slope is the mean log change between the same month of the two years, so it agrees with YoY growth (Spearman 0.84). Every naive figure was too high; the corrected figures (11–23%) bracket the 18.6% of the whole shop (module 27).
  5. rank(...).over("region") adds the rank without collapsing the rows (module 31).

For the director: “Store growth from 2023 to 2024 ranges from 11% (S11 San Francisco) to 23% (S06 Miami), after removing the seasonal pattern. Each store’s figure rests on only two years of data, so treat differences of a few points as noise. S11 is the slowest store, and Denver (S12) opened in its region in mid-2023. These data cannot show whether S12 took sales from S11.”

P4-15 · Interpret a result: is an extra bedroom worth money?

Section titled “P4-15 · Interpret a result: is an extra bedroom worth money?”
Challenge

Interpret a result: a real-estate agent says, “Each extra bedroom adds about 30% to the price.” Check the claim on data/houses.csv with the ten numeric features. Keep the complete rows (the gaps in lot_sqft and school_rating are missing completely at random, MCAR). Standardize the features with broadcasting and compute the correlation matrix from the standardized matrix Z. Use np.linalg.eigh to find its smallest eigenvalue and the features that dominate the weakest direction. Compute the condition number of Z twice, from the eigenvalues and from the singular values of np.linalg.svd. Compute the variance inflation factors (VIF), the diagonal of the inverse correlation matrix, with np.linalg.solve. Then fit three OLS models of log price with HC3 errors: bedrooms only, bedrooms plus sqft, and all ten features. Report the bedroom effect in percent with its 95% CI. Draw the correlation matrix as an annotated heatmap, and a Seaborn pair plot with regression lines for the three size measures and log price. What do you tell the agent?

Expected output
complete rows: 2821 of 3000
smallest eigenvalue 0.104; condition number: eigh 5.45, svd 5.45
its direction: {'bedrooms': 0.72, 'bathrooms': -0.69}
VIF > 2: bedrooms 6.0, bathrooms 5.8, sqft 4.4, distance_to_center_km 2.8, lot_sqft 2.2
bedrooms only: +29.7% per bedroom [+28.0%, +31.4%], R² 0.40
+ sqft: +2.1% per bedroom [+0.0%, +4.2%], R² 0.52
all features: -1.0% per bedroom [-2.4%, +0.5%], R² 0.85
Starter
houses = pd.read_csv("data/houses.csv")
features = ["sqft", "bedrooms", "bathrooms", "year_built", "lot_sqft",
"garage_spaces", "has_pool", "condition", "distance_to_center_km",
"school_rating"]
# TODO: complete rows; Z = standardized features (broadcasting); corr = Z.T @ Z / (n - 1)
# TODO: eigh: smallest eigenvalue, its direction (abs > 0.3); condition number twice
# TODO: VIF = diagonal of solve(corr, identity); print VIF > 2
# TODO: three OLS models of log price; bedroom effect in % with CI and R²
# TODO: annotated heatmap; plt.show(); pair plot with kind="reg"; plt.show()
Hint 1

eigh returns the eigenvalues in ascending order, so eigvals[0] is the smallest and eigvecs[:, 0] its direction. An eigenvector’s sign is arbitrary: flip it so that its largest component is positive, and your output is stable. For the standardized matrix Z, the condition number (largest over smallest singular value) equals the square root of the largest over the smallest eigenvalue of the correlation matrix.

Hint 2

On log price, a coefficient b means a change of exp(b) − 1 per unit, so use np.expm1(b). Apply the same function to both ends of the CI.

Solution
houses = pd.read_csv("data/houses.csv")
features = ["sqft", "bedrooms", "bathrooms", "year_built", "lot_sqft",
"garage_spaces", "has_pool", "condition", "distance_to_center_km",
"school_rating"]
complete = houses.dropna(subset=features) # the gaps are MCAR
print(f"complete rows: {len(complete)} of {len(houses)}")
X = complete[features].to_numpy()
Z = (X - X.mean(axis=0)) / X.std(axis=0, ddof=1) # broadcasting: (n, 10) - (10,)
corr = Z.T @ Z / (len(Z) - 1)
eigvals, eigvecs = np.linalg.eigh(corr) # ascending order
singular = np.linalg.svd(Z, compute_uv=False)
weakest = pd.Series(eigvecs[:, 0], index=features)
weakest *= np.sign(weakest.iloc[weakest.abs().argmax()])
print(f"smallest eigenvalue {eigvals[0]:.3f}; condition number: "
f"eigh {np.sqrt(eigvals[-1] / eigvals[0]):.2f}, "
f"svd {singular[0] / singular[-1]:.2f}")
print("its direction:", weakest[weakest.abs() > 0.3].round(2).to_dict())
vif = pd.Series(np.diag(np.linalg.solve(corr, np.eye(len(features)))), index=features)
high_vif = vif[vif > 2].sort_values(ascending=False)
print("VIF > 2:", ", ".join(f"{name} {v:.1f}" for name, v in high_vif.items()))
data = complete.assign(log_price=np.log(complete["price"]))
specs = {
"bedrooms only": "log_price ~ bedrooms",
"+ sqft": "log_price ~ bedrooms + sqft",
"all features": "log_price ~ " + " + ".join(features),
}
for name, formula in specs.items():
fit = smf.ols(formula, data=data).fit(cov_type="HC3")
b = fit.params["bedrooms"]
low, high = fit.conf_int().loc["bedrooms"]
print(f"{name:>13}: {np.expm1(b):+.1%} per bedroom "
f"[{np.expm1(low):+.1%}, {np.expm1(high):+.1%}], R² {fit.rsquared:.2f}")
fig, ax = plt.subplots(figsize=(8, 6.5), layout="constrained")
sns.heatmap(pd.DataFrame(corr, index=features, columns=features), annot=True,
fmt=".2f", cmap="vlag", vmin=-1, vmax=1, square=True,
cbar_kws={"label": "Pearson r"}, ax=ax)
ax.set_title("Size, bedrooms and bathrooms move together (r ≥ 0.85)")
assert len(complete) == 2821
assert np.isclose(np.sqrt(eigvals[-1] / eigvals[0]), singular[0] / singular[-1])
assert np.allclose(corr, complete[features].corr())
assert set(weakest[weakest.abs() > 0.3].index) == {"bedrooms", "bathrooms"}
assert vif.max() < 10
plt.show()
grid = sns.pairplot(
data[["sqft", "bedrooms", "bathrooms", "log_price"]], kind="reg", corner=True,
height=2.2, plot_kws={"ci": None, "scatter_kws": {"s": 4, "alpha": 0.25}},
)
grid.figure.suptitle("Each size measure predicts log price and the other two")
grid.figure.subplots_adjust(top=0.94)
plt.show()
Output
complete rows: 2821 of 3000
smallest eigenvalue 0.104; condition number: eigh 5.45, svd 5.45
its direction: {'bedrooms': 0.72, 'bathrooms': -0.69}
VIF > 2: bedrooms 6.0, bathrooms 5.8, sqft 4.4, distance_to_center_km 2.8, lot_sqft 2.2
bedrooms only: +29.7% per bedroom [+28.0%, +31.4%], R² 0.40
+ sqft: +2.1% per bedroom [+0.0%, +4.2%], R² 0.52
all features: -1.0% per bedroom [-2.4%, +0.5%], R² 0.85
Annotated correlation heatmap of ten house features: sqft, bedrooms and bathrooms correlate at 0.85 to 0.90; lot size and distance to the center correlate at 0.73; most other pairs are below 0.5.
Correlation matrix of the numeric house features, complete rows.
Corner pair plot of sqft, bedrooms, bathrooms and log price: every pair rises along a regression line, and bedrooms and bathrooms take a few discrete values.
Pair plot with regression lines of the size measures and log price.

How it works:

  1. The data dictionary says the gaps are MCAR, so dropping the 179 incomplete rows loses precision but adds no bias (module 26).
  2. X - X.mean(axis=0) broadcasts a row of 10 means over 2,821 rows. The smallest eigenvalue (0.104) has a direction of almost only bedrooms minus bathrooms: houses rarely differ in one without the other. eigh and svd give the same condition number, 5.45. solve(corr, I) computes the inverse without calling inv (module 23).
  3. Two rules of thumb apply. The largest VIF is 6.0, below the usual VIF alarm of 10. A condition number below 10 counts as weak collinearity; 10–30 is moderate and above 30 is strong. So the collinearity is real but limited to the size block (module 27).
  4. Alone, bedrooms carry the effect of size: +29.7% per bedroom. With sqft in the model, an extra bedroom in a house of the same size adds about 2%. With all features, the effect is −1.0%, and the CI includes zero (module 29).
  5. The heatmap shows the block of size, bedrooms and bathrooms that causes this. Lot size and distance to the center form a second block. The pair plot shows the same block as straight-line clouds between the three size measures, and each of them against log price (module 28).

For the agent: “Bigger houses have more bedrooms, and size is what buyers pay for. At the same floor area, an extra bedroom adds between −2.4% and +0.5% (95% CI, all features), so plan no premium for it. These are averages over 2,821 sales and include 8 known price outliers. A check on one neighborhood needs its own data.”

P4-16 · Choose and justify: should we ship to desktop only?

Section titled “P4-16 · Choose and justify: should we ship to desktop only?”
Challenge

Choose a method and justify it: the checkout test in data/ab_test.csv won overall (+1.5 points, p = 0.013). Now the product manager has a new plan: “Desktop gained 2.5 points and is significant. Tablet went down. Ship to desktop and mobile only.” Check this plan.

Use DuckDB to count users and buyers per device and group. Add the conversion rate with a 95% Wilson CI. For each device, run a two-proportion z-test, correct the three p-values with Benjamini–Hochberg (BH) and compute the power to detect the overall lift with that device’s users. Compute the overall rates and their standardized effect size, Cohen’s h, from the data. Find the users per group that 80% power needs, with NormalIndPower and by hand with stats.norm.ppf. Then test whether the effect differs between devices with one interaction model, converted ~ C(group) * C(device) with HC3, and a Wald test of the interaction terms. Draw the rates with their CIs, save the chart to output/, and answer the product manager.

Expected output
overall: control 0.1012, treatment 0.1166, Cohen's h 0.050
device users lift_pp p p_bh power
desktop 3428 2.459 0.034 0.090 0.308
mobile 5577 1.458 0.060 0.090 0.459
tablet 995 -1.143 0.579 0.579 0.123
users per group for 80% power: 6,344 (by hand 6,344)
interaction test: chi2 = 2.33, df = 2, p = 0.311
Starter
from pathlib import Path
from statsmodels.stats.multitest import multipletests
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import (
proportion_confint,
proportion_effectsize,
proportions_ztest,
)
cells = duckdb.sql("""...""").df() # TODO: users and buyers per device and group
# TODO: rate with Wilson CI; overall rates and Cohen's h
# TODO: per device: lift_pp, z-test p, BH p, power; users for 80% power, two ways
# TODO: OLS with the interaction, Wald test of the interaction terms
# TODO: error-bar chart; savefig to output/ab_segments.png; plt.show()
Hint 1

Three segment tests are three chances to find a false positive. multipletests(p_values, method="fdr_bh")[1] returns the adjusted p-values. Power: proportion_effectsize(p_treatment, p_control) is Cohen’s h of the overall rates; pass nobs1=users / 2 for each device. By hand, each group needs 2 (z1−α/2+z1−β)2/h22\,(z_{1-\alpha/2} + z_{1-\beta})^2 / h^2 users.

Hint 2

A significant lift in one segment and a non-significant lift in another do not show that the effects differ. Only a test of the difference does. In the interaction model, the terms with : measure how much the lift on mobile and tablet differs from the lift on desktop. fit.wald_test("a = 0, b = 0", scalar=True) tests both at once.

Solution
from pathlib import Path
from statsmodels.stats.multitest import multipletests
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import (
proportion_confint,
proportion_effectsize,
proportions_ztest,
)
cells = duckdb.sql("""
SELECT device, "group", COUNT(*) AS users, SUM(converted)::INTEGER AS buyers
FROM 'data/ab_test.csv'
GROUP BY device, "group"
ORDER BY device, "group"
""").df()
cells["rate"] = cells["buyers"] / cells["users"]
low, high = proportion_confint(cells["buyers"], cells["users"], method="wilson")
cells["low"], cells["high"] = low, high
rows = []
for device, part in cells.groupby("device"):
part = part.set_index("group")
_, p = proportions_ztest(
part.loc[["treatment", "control"], "buyers"],
part.loc[["treatment", "control"], "users"],
)
lift = part.loc["treatment", "rate"] - part.loc["control", "rate"]
rows.append({"device": device, "users": part["users"].sum(),
"lift_pp": lift * 100, "p": p})
segments = pd.DataFrame(rows)
segments["p_bh"] = multipletests(segments["p"], method="fdr_bh")[1]
overall = cells.groupby("group")[["buyers", "users"]].sum()
rate = overall["buyers"] / overall["users"]
effect = proportion_effectsize(rate["treatment"], rate["control"]) # Cohen's h
print(f"overall: control {rate['control']:.4f}, treatment {rate['treatment']:.4f}, "
f"Cohen's h {effect:.3f}")
segments["power"] = [
NormalIndPower().power(effect, nobs1=n / 2, alpha=0.05) for n in segments["users"]
]
print(segments.round(3).to_string(index=False))
need = NormalIndPower().solve_power(effect, power=0.8, alpha=0.05)
z_sum = stats.norm.ppf(1 - 0.05 / 2) + stats.norm.ppf(0.8)
by_hand = 2 * (z_sum / effect) ** 2 # two groups of equal size
print(f"users per group for 80% power: {need:,.0f} (by hand {by_hand:,.0f})")
ab = pd.read_csv("data/ab_test.csv")
fit = smf.ols("converted ~ C(group) * C(device)", data=ab).fit(cov_type="HC3")
terms = [name for name in fit.params.index if ":" in name]
wald = fit.wald_test(", ".join(f"{t} = 0" for t in terms), scalar=True)
print(f"interaction test: chi2 = {wald.statistic:.2f}, df = {len(terms)}, "
f"p = {wald.pvalue:.3f}")
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
x = np.arange(3)
for shift, (group, part) in zip([-0.1, 0.1], cells.groupby("group"), strict=True):
errors = [part["rate"] - part["low"], part["high"] - part["rate"]]
ax.errorbar(x + shift, part["rate"] * 100, yerr=np.array(errors) * 100,
fmt="o", capsize=4, label=group)
ax.set_xticks(x, sorted(cells["device"].unique()))
ax.set(ylim=(0, 18), ylabel="Conversion (%), 95% Wilson CI",
title="No device shows a lift that survives the checks")
ax.legend()
Path("output").mkdir(exist_ok=True)
fig.savefig("output/ab_segments.png", dpi=200, bbox_inches="tight")
assert cells["users"].sum() == 10_000
assert (segments["p_bh"] > 0.05).all()
assert wald.pvalue > 0.05
assert np.isclose(need, by_hand)
plt.show()
Output
overall: control 0.1012, treatment 0.1166, Cohen's h 0.050
device users lift_pp p p_bh power
desktop 3428 2.459 0.034 0.090 0.308
mobile 5577 1.458 0.060 0.090 0.459
tablet 995 -1.143 0.579 0.579 0.123
users per group for 80% power: 6,344 (by hand 6,344)
interaction test: chi2 = 2.33, df = 2, p = 0.311
Conversion rate per device with 95% Wilson intervals: treatment is higher on desktop (14.5% against 12.0%) and mobile (10.0% against 8.5%), lower on tablet (11.4% against 12.5%), and the tablet intervals are very wide.
Conversion per device and group with 95% Wilson confidence intervals.

How it works:

  1. DuckDB aggregates the CSV file directly. SUM(converted)::INTEGER keeps the buyer counts as integers (module 30).
  2. Wilson intervals stay sensible for rates near 10% and small groups. The tablet intervals are about 6 points wide (module 29).
  3. Desktop’s p = 0.034 becomes 0.090 after the BH correction. No segment is significant on its own once you count the three looks.
  4. Power is the key number: with 995 users, the tablet test had a 12% chance to detect the overall lift. Its negative result is uninformative: it is not evidence of harm. Even the whole test, with 5,000 users per group, was below the 6,344 per group that 80% power needs. stats.norm.ppf gives the two z-values of the formula, and the hand calculation matches statsmodels.
  5. The interaction test asks the real question, “Does the lift differ by device?”, and finds no evidence (p = 0.311).
  6. savefig before plt.show() writes the chart for the slide deck (module 28).

For the product manager: “Ship to all devices. The test shows one overall lift of about 1.5 points. The device differences are within the noise of the smaller segments (interaction test p = 0.31), and tablet had only 12% power. If tablet matters, run a dedicated test with enough users. To detect the overall lift with 80% power, it needs about 6,300 users per group.”

Rate yourself on each skill after you finish the exercises. Base the rating on what you did without the solution.

Skill area Not yet Getting there Ready
23. NumPy: arrays, axes, linear algebra You loop over rows in Python. You vectorize, but a view, an int8 overflow or a NaN surprises you. You predict views, copies, dtypes and NaN results, broadcast, split and fancy-index arrays, fit many targets with one lstsq call, and use eigh, svd and solve to check collinearity.
24. pandas fundamentals You fix types by hand after loading. You load and filter, but & versus | or a coerced gap slips through. You declare missing tokens at load time, read JSON and write and read Excel and Parquet, filter with masks and query, look up with map, and build ordered categoricals.
25. pandas advanced: groupby, reshape, merge, windows You copy numbers between tables by hand. You group and pivot, but a crosstab normalizes the wrong way or a merge fans out. You use named aggregation, transform and filter, a MultiIndex with xs, unstack, stack and melt, concat, join and merge with validate, rolling, expanding and EWM windows, and category dtypes to cut memory.
26. Data cleaning You clean in place and cannot say what changed. You clean, but mixed dates, a wrong key or band edges lose rows. You parse each date format strictly, deduplicate on the right key, choose an imputation by its error on hidden values, compare IQR and z-score rules with context, and prove the cleaning against a trusted source.
27. EDA You report a correlation as a cause. You spot skew and outliers, but miss a confounder. You normalize for exposure (days on sale), find confounders by stratifying, and write findings as claim → evidence → caveat.
28. Visualization You plot with the defaults and no labels. You label charts, but choose the chart before the question. You choose the chart for the question, build Matplotlib grids with formatted ticks and annotations, use Seaborn bar, distribution, faceted and pair plots and Plotly, avoid overplotting and save charts to output/.
29. Statistics You report only p-values. You run tests, but cannot say which one fits or what a CI means. You fit a distribution and use its sf and ppf, show the CLT by simulation, choose Welch, Mann–Whitney, ANOVA, Kruskal–Wallis or chi-square by the data, report effect sizes (eta squared, Cohen’s h) and CIs, and correct for multiple tests and check power.
30. SQL: SQLite and DuckDB You load every table into pandas first. You write queries, but build them with f-strings or let joins fan out. You pass values with placeholders, aggregate in CTEs before joining, use PARTITION BY with RANK and LAG, move data with to_sql and read_sql_query, use DuckDB on files and DataFrames, and check SQL against pandas.
31. Polars You translate pandas line by line. You write expressions, but forget that group order is not stable. You write lazy queries, when/then/otherwise, pivot, joins with validate and over windows, and sort every result before you compare it.

You are ready for Part 5 when you can:

  • Solve at least 11 of the 16 exercises without opening the solution, including one challenge.
  • Predict all 7 lines of P4-01, and explain each one with the rule behind it.
  • Find the bugs in a cleaning script by reconciling its result with a trusted source.
  • Load nested JSON, check it against reference tables and hand it over as a multi-sheet Excel file.
  • Compute the same summary with pandas, a SQL query and Polars, and show with assert_frame_equal that they agree.
  • Rank, share and compare years in SQL with window functions.
  • Reshape a table between long, wide and MultiIndex forms without losing a value.
  • Choose an imputation and an outlier rule on evidence, and explain why a detrended rule beats a raw one.
  • Choose a test and a chart for a question from the types of the data, and justify both in one sentence.
  • Report an effect size with a confidence interval (bootstrap, Wilson or OLS), not only a p-value.
  • Find a confounder by stratifying, and adjust for it with a regression.
  • Explain why a significant segment result does not show that segments differ, and test the interaction instead.
  • Remove seasonality before you estimate a growth rate, and fit many series at once with NumPy.
  • Spot collinear features with a correlation matrix, eigenvalues and VIF, and explain how they change a coefficient.
  • Write a conclusion as claim → evidence → caveat that a manager can act on.

Rated “Not yet” in a row? Review that module’s lesson and cheat sheet, redo two of its core exercises, then try the matching checkpoint exercise again. When every row reads “Getting there” or “Ready”, move on to Part 5, module 32: Math for machine learning. Part 5 builds directly on these skills: the linear algebra of lstsq, eigh and svd returns as regression and PCA, the train-test thinking grows out of the bootstrap and the CIs, and every model starts with the cleaning and EDA of this Part.