Skip to content

27. Exploratory data analysis — Exercises

These exercises practice every idea of the exploratory data analysis lesson. They use three course datasets: data/customers.csv (churn), data/houses.csv (prices) and data/sales.csv (order lines).

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block and the starter code into a script and replace each to-do comment with your code.
  3. Run the script and compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Each solution ends with assert checks. Add the same checks to your own code. Several exercises ask you to interpret a result or to choose a method: the explanation in the solution matters as much as the code.

Every exercise starts from this block. It loads the three tables and fixes the display. Run it at the top of each script.

import numpy as np
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
customers = pd.read_csv("data/customers.csv")
houses = pd.read_csv("data/houses.csv")
sales = pd.read_csv("data/sales.csv")

M27-W01 · Find the columns with missing values

Section titled “M27-W01 · Find the columns with missing values”
Warm-up

Check 2 of the EDA checklist on houses. Print one line per column that has missing values: its name, the number of blanks and the share in percent with one decimal. Skip complete columns.

Expected output
lot_sqft: 90 missing (3.0%)
school_rating: 90 missing (3.0%)
Starter
counts = houses.isna().sum()
# TODO: keep only the columns with at least one blank
# TODO: print name, count and share for each
Hint 1

counts[counts > 0] keeps only the columns with gaps. The share is count / len(houses).

Hint 2

Loop with for column, count in gaps.items(): and format the share with :.1%.

Solution
counts = houses.isna().sum()
gaps = counts[counts > 0]
for column, count in gaps.items():
print(f"{column}: {count} missing ({count / len(houses):.1%})")
assert gaps.to_dict() == {"lot_sqft": 90, "school_rating": 90}
Output
lot_sqft: 90 missing (3.0%)
school_rating: 90 missing (3.0%)

How it works:

  1. isna() gives a table of True/False. sum() counts the True values per column.
  2. The boolean filter counts > 0 keeps the two columns with gaps.
  3. items() yields (name, count) pairs, and :.1% multiplies by 100 and adds the percent sign.

Alternative: houses.isna().mean() gives the shares directly, because the mean of True/False values is the share of True.

shares = houses.isna().mean()
print(shares[shares > 0].round(3))
Output
lot_sqft 0.03
school_rating 0.03
dtype: float64
Warm-up

Print the share of each value of churned in customers as a percentage with two decimals. Then print the accuracy of a “baseline” that always predicts the larger class.

Expected output
churned=0: 80.74%
churned=1: 19.26%
baseline accuracy: 80.74%
Starter
# TODO: shares of churned with value_counts(normalize=True)
# TODO: print each share as a percentage
# TODO: print the baseline accuracy (share of the larger class)
Hint 1

customers["churned"].value_counts(normalize=True) returns the shares, largest first.

Hint 2

The baseline that always predicts the larger class is right exactly as often as that class occurs: shares.max().

Solution
shares = customers["churned"].value_counts(normalize=True)
for value, share in shares.items():
print(f"churned={value}: {share:.2%}")
baseline = shares.max()
print(f"baseline accuracy: {baseline:.2%}")
assert round(shares[1], 4) == 0.1926
assert shares.index[0] == 0
Output
churned=0: 80.74%
churned=1: 19.26%
baseline accuracy: 80.74%

How it works:

  1. normalize=True divides each count by the number of rows, so the shares add up to 1.
  2. :.2% shows the share as a percentage with two decimals.
  3. A model must beat 80.74% accuracy to be better than “nobody churns”. With a rare class, accuracy is a weak score.
Warm-up

For monthly_charges in customers, print the mean, the median and the skewness with two decimals. Then print right-skewed when the skew is above 0.5, left-skewed when it is below −0.5, and roughly symmetric otherwise.

Expected output
mean 60.84 median 58.86 skew 0.62
right-skewed
Starter
charges = customers["monthly_charges"]
# TODO: compute mean, median and skew
# TODO: choose the label with if/elif/else and print it
Hint 1

charges.mean(), charges.median() and charges.skew() each return one number.

Hint 2

Test skew > 0.5 first, then skew < -0.5, then else.

Solution
charges = customers["monthly_charges"]
mean, median, skew = charges.mean(), charges.median(), charges.skew()
print(f"mean {mean:.2f} median {median:.2f} skew {skew:.2f}")
if skew > 0.5:
label = "right-skewed"
elif skew < -0.5:
label = "left-skewed"
else:
label = "roughly symmetric"
print(label)
assert label == "right-skewed"
assert mean > median
Output
mean 60.84 median 58.86 skew 0.62
right-skewed

How it works:

  1. The mean is about 2 above the median: the premium plan’s high charges form a right tail.
  2. The skew of 0.62 is moderate, so the label is right-skewed.
  3. The assert mean > median checks the direction that the skew predicts.

M27-W04 · Read the quantiles of a count column

Section titled “M27-W04 · Read the quantiles of a count column”
Warm-up

Print the 10%, 25%, 50%, 75%, 90% and 99% quantiles of logins_last_30d, then the interquartile range (Q3 − Q1).

Expected output
0.10 4.0
0.25 6.0
0.50 10.0
0.75 15.0
0.90 21.0
0.99 41.0
Name: logins_last_30d, dtype: float64
IQR: 9.0
Starter
logins = customers["logins_last_30d"]
# TODO: quantiles at 0.1, 0.25, 0.5, 0.75, 0.9 and 0.99
# TODO: IQR = Q3 - Q1
Hint 1

logins.quantile([0.1, 0.25, ...]) returns a Series indexed by the probabilities.

Hint 2

Read Q1 and Q3 from that Series with q[0.25] and q[0.75].

Solution
logins = customers["logins_last_30d"]
q = logins.quantile([0.1, 0.25, 0.5, 0.75, 0.9, 0.99])
print(q)
iqr = q[0.75] - q[0.25]
print(f"IQR: {iqr}")
assert iqr == 9.0
assert q[0.99] < logins.max()
Output
0.10 4.0
0.25 6.0
0.50 10.0
0.75 15.0
0.90 21.0
0.99 41.0
Name: logins_last_30d, dtype: float64
IQR: 9.0

How it works:

  1. quantile with a list returns one value per probability.
  2. Half of the customers log in between 6 and 15 times a month (the IQR is 9).
  3. The 99% quantile (41) is far below the maximum (60): a few very active customers form a long right tail.
Warm-up

Predict the output: six days of sign-ups rise every day, but the last day has a viral spike. Which coefficient prints exactly 1.000? Is the other one higher or lower than 0.9?

Starter
day = pd.Series([1, 2, 3, 4, 5, 6])
signups = pd.Series([10, 12, 13, 15, 16, 90])
print(f"Pearson: {day.corr(signups):.3f}")
print(f"Spearman: {day.corr(signups, method='spearman'):.3f}")

Acceptance criteria:

  • Write down your prediction for both lines, then run the code.
  • Your prediction names the coefficient that is exactly 1 and says whether the other one is above or below 0.9.
Hint 1

Spearman looks only at the ranks. Do the ranks of signups follow the ranks of day exactly?

Hint 2

Pearson measures how close the points lie to one straight line. Five points sit on a gentle line and one sits far above it.

Solution
day = pd.Series([1, 2, 3, 4, 5, 6])
signups = pd.Series([10, 12, 13, 15, 16, 90])
pearson = day.corr(signups)
spearman = day.corr(signups, method="spearman")
print(f"Pearson: {pearson:.3f}")
print(f"Spearman: {spearman:.3f}")
assert spearman == 1.0
assert pearson < 0.9
Output
Pearson: 0.704
Spearman: 1.000

How it works:

  1. Sign-ups rise every day, so their ranks are 1 to 6, the same as the ranks of day. Spearman is exactly 1.
  2. The spike on day 6 lies far above the line through the first five points. No straight line fits all six well, so Pearson drops to about 0.70.
  3. The trend is perfectly monotonic but not linear. Spearman describes it; Pearson describes the spike.

M27-W06 · Compare line share and revenue share by region

Section titled “M27-W06 · Compare line share and revenue share by region”
Warm-up

For each region in sales, print the share of order lines and the share of revenue, both rounded to three decimals, in one table sorted by revenue share.

Expected output
lines revenue
region
East 0.267 0.276
South 0.254 0.248
North 0.246 0.247
West 0.233 0.229
Starter
# TODO: line share per region with value_counts(normalize=True)
# TODO: revenue share per region with groupby + sum, divided by the total
# TODO: combine both in one DataFrame and sort
Hint 1

sales["region"].value_counts(normalize=True) gives the line shares.

Hint 2

revenue = sales.groupby("region")["revenue"].sum(), then revenue / revenue.sum(). Put both Series in pd.DataFrame({"lines": ..., "revenue": ...}); pandas aligns them by region.

Solution
line_share = sales["region"].value_counts(normalize=True)
revenue = sales.groupby("region")["revenue"].sum()
table = pd.DataFrame({"lines": line_share, "revenue": revenue / revenue.sum()})
table = table.sort_values("revenue", ascending=False).round(3)
print(table)
assert table.index[0] == "East"
assert abs(table["revenue"].sum() - 1) < 0.002
Output
lines revenue
region
East 0.267 0.276
South 0.254 0.248
North 0.246 0.247
West 0.233 0.229

How it works:

  1. The two Series have the same index (the four regions), so the DataFrame lines them up by name.
  2. East leads both columns. The regions are close: no region dominates as Electronics does among categories.
  3. The assert on the sum allows for rounding to three decimals.
Warm-up

Fix the bug: the analyst wants “the churn rate of each plan”. The code below runs, but the printed numbers answer a different question. Fix the call and print the churn rate per plan (column 1 only), sorted from high to low.

Expected output
plan
premium 0.296
basic 0.174
standard 0.160
Name: 1, dtype: float64
Starter
table = pd.crosstab(customers["plan"], customers["churned"], normalize="columns")
print(table)
# TODO: fix normalize so that each plan's row adds up to 1
# TODO: print column 1, sorted from high to low
Hint 1

With normalize="columns", each column adds up to 1. Column 1 then says “of all churners, what share is on each plan”.

Hint 2

You want each plan’s row to add up to 1: normalize="index".

Solution
table = pd.crosstab(customers["plan"], customers["churned"], normalize="index")
churn_rate = table[1].sort_values(ascending=False)
print(churn_rate.round(3))
assert churn_rate.index[0] == "premium"
assert np.allclose(table.sum(axis=1), 1)
Output
plan
premium 0.296
basic 0.174
standard 0.160
Name: 1, dtype: float64

How it works:

  1. With normalize="index", each row adds up to 1, so the 1 column holds the churn rate of each plan.
  2. The buggy version gave the plan mix of the churners. Basic has the most churners only because it has the most customers.
  3. The assert table.sum(axis=1) checks the direction of the normalization.

Alternative: the mean of a 0/1 column is its rate, so a groupby gives the same numbers.

rates = customers.groupby("plan")["churned"].mean()
print(rates.sort_values(ascending=False).round(3))
Output
plan
premium 0.296
basic 0.174
standard 0.160
Name: churned, dtype: float64

M27-W08 · Median price per neighborhood with counts

Section titled “M27-W08 · Median price per neighborhood with counts”
Warm-up

Print the number of sales and the median price of each neighborhood in houses, sorted by median price from high to low.

Expected output
sales median_price
neighborhood
Lakeview 307 777000.0
Oak Hill 380 724500.0
Riverside 370 476750.0
Maple Grove 454 402750.0
Downtown 356 341750.0
Old Town 276 335250.0
Westfield 450 266750.0
Cedar Park 407 249000.0
Starter
# TODO: groupby neighborhood, agg count and median of price
# TODO: sort by the median, high to low
Hint 1

houses.groupby("neighborhood")["price"].agg(["size", "median"]) gives both columns.

Hint 2

Named aggregation gives clearer column names: .agg(sales="size", median_price="median").

Solution
grouped = houses.groupby("neighborhood")["price"]
summary = grouped.agg(sales="size", median_price="median")
summary = summary.sort_values("median_price", ascending=False)
print(summary)
assert summary.index[0] == "Lakeview"
assert summary["sales"].sum() == len(houses)
Output
sales median_price
neighborhood
Lakeview 307 777000.0
Oak Hill 380 724500.0
Riverside 370 476750.0
Maple Grove 454 402750.0
Downtown 356 341750.0
Old Town 276 335250.0
Westfield 450 266750.0
Cedar Park 407 249000.0

How it works:

  1. Named aggregation (name="function") sets the output column names.
  2. The median is the right center for a skewed price. Lakeview’s median is about three times Cedar Park’s.
  3. Every group has more than 250 sales, so the medians are stable.

M27-W09 · Check the keys of the sales table

Section titled “M27-W09 · Check the keys of the sales table”
Warm-up

Check 3 of the checklist on sales. Print how many order_id values repeat, how many (order_id, product_id) pairs repeat, and the share of orders with 1, 2 and 3 lines.

Expected output
repeated order_id: 5351
repeated (order_id, product_id): 0
1 0.724
2 0.193
3 0.083
Name: proportion, dtype: float64
Starter
# TODO: repeated order_id values with duplicated().sum()
# TODO: repeated (order_id, product_id) pairs with duplicated(subset=[...]).sum()
# TODO: lines per order, then value_counts(normalize=True)
Hint 1

sales["order_id"].duplicated() is True for each repeat after the first occurrence.

Hint 2

sales.groupby("order_id").size() counts the lines of each order. Then use value_counts(normalize=True).sort_index().

Solution
repeated_ids = sales["order_id"].duplicated().sum()
repeated_pairs = sales.duplicated(subset=["order_id", "product_id"]).sum()
lines_per_order = sales.groupby("order_id").size()
print(f"repeated order_id: {repeated_ids}")
print(f"repeated (order_id, product_id): {repeated_pairs}")
print(lines_per_order.value_counts(normalize=True).sort_index().round(3))
assert repeated_pairs == 0
assert repeated_ids == len(sales) - sales["order_id"].nunique()
Output
repeated order_id: 5351
repeated (order_id, product_id): 0
1 0.724
2 0.193
3 0.083
Name: proportion, dtype: float64

How it works:

  1. order_id repeats 5,351 times, because one order has up to three lines. It is not the key of this table.
  2. The pair (order_id, product_id) never repeats, so it is the key: one row is one product within one order.
  3. 72.4% of orders have one line. Any “per order” statistic must group by order_id first.

M27-C01 · Write a numeric profile function

Section titled “M27-C01 · Write a numeric profile function”
Core

Write profile(values: pd.Series) -> pd.Series that returns count, missing, mean, median, std, skew, and the 1% and 99% quantiles (named p01 and p99). Apply it to sqft, lot_sqft and the price in thousands (price / 1000, named price_k) of houses, and print one row per column, rounded to one decimal.

Expected output
count missing mean median std skew p01 p99
sqft 3000.0 0.0 1856.6 1740.0 711.9 1.1 680.0 4160.1
lot_sqft 2910.0 90.0 8309.7 7530.0 4901.1 1.1 1541.8 23970.1
price_k 3000.0 0.0 476.5 376.0 318.8 2.7 167.0 1765.7
Starter
def profile(values: pd.Series) -> pd.Series:
# TODO: return a Series with the eight statistics
...
numbers = houses[["sqft", "lot_sqft"]].assign(price_k=houses["price"] / 1000)
# TODO: apply profile to the three columns and build a DataFrame
Hint 1

Build the result with pd.Series({"count": values.count(), "missing": values.isna().sum(), ...}).

Hint 2

numbers.apply(profile) calls profile once per column and gives the statistics as rows. .T turns them into columns.

Solution
def profile(values: pd.Series) -> pd.Series:
"""Center, spread, shape and tails of one numeric column."""
return pd.Series(
{
"count": values.count(),
"missing": values.isna().sum(),
"mean": values.mean(),
"median": values.median(),
"std": values.std(),
"skew": values.skew(),
"p01": values.quantile(0.01),
"p99": values.quantile(0.99),
}
)
numbers = houses[["sqft", "lot_sqft"]].assign(price_k=houses["price"] / 1000)
table = numbers.apply(profile).T.round(1)
print(table)
assert table.loc["lot_sqft", "missing"] == 90
assert (table["skew"] > 1).all()
Output
count missing mean median std skew p01 p99
sqft 3000.0 0.0 1856.6 1740.0 711.9 1.1 680.0 4160.1
lot_sqft 2910.0 90.0 8309.7 7530.0 4901.1 1.1 1541.8 23970.1
price_k 3000.0 0.0 476.5 376.0 318.8 2.7 167.0 1765.7

How it works:

  1. count() counts non-missing values; isna().sum() counts the missing ones. Together they give the row count.
  2. apply(profile) runs the function on each column. The result has one column per input column, so .T makes one row per column.
  3. All three columns are right-skewed (skew above 1). The mean is above the median in each row. Dividing the price by 1,000 keeps pandas from switching the table to scientific notation.
Core

Split tenure_months into the bands 0, 1-3, 4-6, 7-12, 13-24, 25-48 and 49-72 with pd.cut. Print the churn rate (three decimals) and the number of customers per band. Then print the ratio of the churn rate in band 1-3 to the rate in band 49-72, with one decimal.

Expected output
mean size
tenure_months
0 0.000 10
1-3 0.547 616
4-6 0.312 484
7-12 0.196 857
13-24 0.142 1192
25-48 0.094 1181
49-72 0.041 660
1-3 months churn 13.4x as often as 49-72 months
Starter
bins = [-1, 0, 3, 6, 12, 24, 48, 72]
labels = ["0", "1-3", "4-6", "7-12", "13-24", "25-48", "49-72"]
# TODO: band = pd.cut(...)
# TODO: churn rate and size per band
# TODO: ratio of the first-quarter rate to the 49-72 rate
Hint 1

pd.cut uses right-closed intervals: (-1, 0] holds only 0 and (0, 3] holds 1 to 3.

Hint 2

customers.groupby(band, observed=True)["churned"].agg(["mean", "size"]). Read a rate with .loc["1-3", "mean"].

Solution
bins = [-1, 0, 3, 6, 12, 24, 48, 72]
labels = ["0", "1-3", "4-6", "7-12", "13-24", "25-48", "49-72"]
band = pd.cut(customers["tenure_months"], bins=bins, labels=labels)
by_band = customers.groupby(band, observed=True)["churned"].agg(["mean", "size"])
print(by_band.round(3))
ratio = by_band.loc["1-3", "mean"] / by_band.loc["49-72", "mean"]
print(f"1-3 months churn {ratio:.1f}x as often as 49-72 months")
assert by_band["size"].sum() == len(customers)
assert by_band["mean"].iloc[1:].is_monotonic_decreasing
Output
mean size
tenure_months
0 0.000 10
1-3 0.547 616
4-6 0.312 484
7-12 0.196 857
13-24 0.142 1192
25-48 0.094 1181
49-72 0.041 660
1-3 months churn 13.4x as often as 49-72 months

How it works:

  1. The bin edges start at −1, so tenure 0 falls into the first band (-1, 0].
  2. Churn falls with every band after the first: from 54.7% in the first three months to 4.1% after four years. The fall is steep at first and then flattens, a curve that one correlation cannot describe.
  3. Band 0 has 10 customers, none churned. They are the brand-new customers from the lesson, too few and too new to judge.
Core

Interpret a result: the Pearson correlation between logins_last_30d and churned is weak. Print it with three decimals. Then bin logins into 0-3, 4-6, 7-10, 11-15 and 16+, print the churn rate and size per bin, and print one sentence that interprets the pattern.

Expected output
Pearson r: -0.096
mean size
logins_last_30d
0-3 0.425 395
4-6 0.185 942
7-10 0.177 1295
11-15 0.185 1176
16+ 0.147 1192
Threshold effect: 42.5% churn at 0-3 logins, 14.7%-18.5% above that.
Starter
# TODO: Pearson correlation of logins and churned
# TODO: bins [-1, 3, 6, 10, 15, 60] with the labels above
# TODO: churn rate and size per bin
# TODO: print an interpretation
Hint 1

Use the same pd.cut + groupby(..., observed=True) pattern as in M27-C02.

Hint 2

Compare the first bin with all the others. Is the change gradual, or is there a threshold?

Solution
r = customers["logins_last_30d"].corr(customers["churned"])
print(f"Pearson r: {r:.3f}")
bins = [-1, 3, 6, 10, 15, 60]
labels = ["0-3", "4-6", "7-10", "11-15", "16+"]
band = pd.cut(customers["logins_last_30d"], bins=bins, labels=labels)
by_band = customers.groupby(band, observed=True)["churned"].agg(["mean", "size"])
print(by_band.round(3))
low, rest = by_band["mean"].iloc[0], by_band["mean"].iloc[1:]
print(
f"Threshold effect: {low:.1%} churn at 0-3 logins, "
f"{rest.min():.1%}-{rest.max():.1%} above that."
)
assert low > 2 * rest.max()
Output
Pearson r: -0.096
mean size
logins_last_30d
0-3 0.425 395
4-6 0.185 942
7-10 0.177 1295
11-15 0.185 1176
16+ 0.147 1192
Threshold effect: 42.5% churn at 0-3 logins, 14.7%-18.5% above that.

How it works:

  1. The correlation is close to 0, so a correlation table would rank logins as unimportant.
  2. The bins show a threshold: customers with 0–3 logins churn far more, and above 3 logins the rate barely changes.
  3. A step like this gives a small Pearson value, because most customers sit on the flat part. The useful feature is the flag logins_last_30d <= 3, not the raw count.
Core

Refactor: the loop below computes the churn rate per payment method. Replace it with one vectorized pandas expression that also returns the number of customers and the lift (rate divided by the overall churn rate). Check that both versions give the same rates.

Expected output
rate customers lift
payment_method
electronic_check 0.248 1563 1.286
paypal 0.174 868 0.903
bank_transfer 0.174 1209 0.902
credit_card 0.158 1360 0.821
Starter
rates = {}
for method in sorted(customers["payment_method"].unique()):
group = customers[customers["payment_method"] == method]
rates[method] = group["churned"].sum() / len(group)
print(rates)
# TODO: one groupby with rate and size, plus a lift column
Hint 1

groupby("payment_method")["churned"].agg(rate="mean", customers="size") gives two columns in one pass.

Hint 2

The overall rate is customers["churned"].mean(). Divide the rate column by it.

Solution
rates = {}
for method in sorted(customers["payment_method"].unique()):
group = customers[customers["payment_method"] == method]
rates[method] = group["churned"].sum() / len(group)
grouped = customers.groupby("payment_method")["churned"]
table = grouped.agg(rate="mean", customers="size")
table["lift"] = table["rate"] / customers["churned"].mean()
print(table.sort_values("lift", ascending=False).round(3))
assert np.allclose(table["rate"], pd.Series(rates))
Output
rate customers lift
payment_method
electronic_check 0.248 1563 1.286
paypal 0.174 868 0.903
bank_transfer 0.174 1209 0.902
credit_card 0.158 1360 0.821

How it works:

  1. The loop filters the full table once per method. The groupby splits the table once and computes all groups together.
  2. The mean of a 0/1 column is the share of 1s, so mean is the churn rate.
  3. Electronic check has a lift of about 1.29: those customers churn 29% more often than average. np.allclose compares the floats from both versions with a tolerance.

M27-C05 · Choose the normalization of a crosstab

Section titled “M27-C05 · Choose the normalization of a crosstab”
Core

Choose a method and justify: answer two questions with pd.crosstab(customers["contract"], customers["plan"], ...). (a) “What plan mix does each contract type have?” (b) “Of the premium customers, what share are on a month-to-month contract?” Print the counts with margins first, then the table for (a), then the answer to (b).

Expected output
plan basic premium standard All
contract
month-to-month 1172 530 1082 2784
one-year 468 248 509 1225
two-year 388 212 391 991
All 2028 990 1982 5000
plan basic premium standard
contract
month-to-month 0.421 0.190 0.389
one-year 0.382 0.202 0.416
two-year 0.392 0.214 0.395
(b) month-to-month share of premium customers: 53.5%
Starter
# TODO: counts with margins=True
# TODO: (a) normalize so that each contract row adds up to 1
# TODO: (b) normalize so that each plan column adds up to 1
# TODO: print the share of month-to-month among premium customers
Hint 1

Question (a) compares rows (contracts), so each row must add up to 1. Question (b) starts from a column (premium), so each column must add up to 1.

Hint 2

normalize="index" for (a), normalize="columns" for (b). Read (b) with .loc["month-to-month", "premium"].

Solution
contract, plan = customers["contract"], customers["plan"]
counts = pd.crosstab(contract, plan, margins=True)
print(counts)
by_contract = pd.crosstab(contract, plan, normalize="index")
by_plan = pd.crosstab(contract, plan, normalize="columns")
print(by_contract.round(3))
answer_b = by_plan.loc["month-to-month", "premium"]
print(f"(b) month-to-month share of premium customers: {answer_b:.1%}")
assert np.allclose(by_contract.sum(axis=1), 1)
assert np.allclose(by_plan.sum(axis=0), 1)
Output
plan basic premium standard All
contract
month-to-month 1172 530 1082 2784
one-year 468 248 509 1225
two-year 388 212 391 991
All 2028 990 1982 5000
plan basic premium standard
contract
month-to-month 0.421 0.190 0.389
one-year 0.382 0.202 0.416
two-year 0.392 0.214 0.395
(b) month-to-month share of premium customers: 53.5%

How it works:

  1. The counts with margins show the raw sizes: 990 premium customers, 2,784 on month-to-month.
  2. (a) The plan mix is almost the same for every contract type (about 19–21% premium). Plan and contract are nearly independent.
  3. (b) Of the 990 premium customers, 53.5% are on a month-to-month contract. That is a column share, so normalize="columns" answers it.

M27-C06 · Pivot the churn rate by contract and payment method

Section titled “M27-C06 · Pivot the churn rate by contract and payment method”
Core

Build a pivot table of the churn rate with contract in the rows and payment_method in the columns. Print it with three decimals. Then print the highest and the lowest cell with their row and column labels.

Expected output
payment_method bank_transfer credit_card electronic_check paypal
contract
month-to-month 0.273 0.250 0.370 0.265
one-year 0.088 0.065 0.117 0.073
two-year 0.013 0.019 0.064 0.023
highest: ('month-to-month', 'electronic_check') 37.0% (n=873)
lowest: ('two-year', 'bank_transfer') 1.3% (n=236)
Starter
# TODO: pivot_table with values="churned", aggfunc="mean"
# TODO: stack() the table into one Series of cells
# TODO: idxmax() / idxmin() give the (row, column) labels
Hint 1

customers.pivot_table(index="contract", columns="payment_method", values="churned", aggfunc="mean").

Hint 2

cells = pivot.stack() has a two-level index. cells.idxmax() returns a tuple (contract, method).

Solution
pivot = customers.pivot_table(
index="contract", columns="payment_method", values="churned", aggfunc="mean"
)
print(pivot.round(3))
cells = pivot.stack()
high, low = cells.idxmax(), cells.idxmin()
sizes = customers.pivot_table(
index="contract", columns="payment_method", values="churned", aggfunc="size"
).stack()
print(f"highest: {high} {cells[high]:.1%} (n={sizes[high]})")
print(f"lowest: {low} {cells[low]:.1%} (n={sizes[low]})")
assert high == ("month-to-month", "electronic_check")
assert low[0] == "two-year"
Output
payment_method bank_transfer credit_card electronic_check paypal
contract
month-to-month 0.273 0.250 0.370 0.265
one-year 0.088 0.065 0.117 0.073
two-year 0.013 0.019 0.064 0.023
highest: ('month-to-month', 'electronic_check') 37.0% (n=873)
lowest: ('two-year', 'bank_transfer') 1.3% (n=236)

How it works:

  1. Each cell is the churn rate of one contract × payment combination.
  2. stack() turns the 3 × 4 table into a Series of 12 cells with a (contract, method) index, so idxmax and idxmin return both labels.
  3. The highest cell (37.0%, n=873) is far above the lowest (1.3%, n=236). Two features together separate customers much better than either alone.
  4. Do not quote the ratio of the two cells. The lowest cell has only about 3 churners, so one more churner would change it by 0.4 points and the ratio by a third.

M27-C07 · Measure how two bad rows move a correlation

Section titled “M27-C07 · Measure how two bad rows move a correlation”
Core

In the Old Town neighborhood of houses, the data dictionary lists two injected outliers: H2277 and H0957. Print Pearson and Spearman between sqft and price for Old Town with and without these two rows, and the change of each coefficient.

Expected output
with without change
pearson 0.569 0.615 0.046
spearman 0.623 0.633 0.010
Starter
old_town = houses[houses["neighborhood"] == "Old Town"]
bad = ["H2277", "H0957"]
# TODO: clean = old_town without the bad rows (isin)
# TODO: both coefficients for both frames, and the change
Hint 1

old_town[~old_town["house_id"].isin(bad)] drops the two rows.

Hint 2

Store the four values in a small dict or DataFrame, then subtract.

Solution
old_town = houses[houses["neighborhood"] == "Old Town"]
bad = ["H2277", "H0957"]
clean = old_town[~old_town["house_id"].isin(bad)]
result = pd.DataFrame(
{
name: {
"pearson": frame["sqft"].corr(frame["price"]),
"spearman": frame["sqft"].corr(frame["price"], method="spearman"),
}
for name, frame in [("with", old_town), ("without", clean)]
}
)
result["change"] = result["without"] - result["with"]
print(result.round(3))
assert len(clean) == len(old_town) - 2
assert abs(result.loc["pearson", "change"]) > abs(result.loc["spearman", "change"])
Output
with without change
pearson 0.569 0.615 0.046
spearman 0.623 0.633 0.010

How it works:

  1. The dict comprehension builds one column per frame and one row per coefficient.
  2. Two rows of 276 move Pearson by 0.046. Spearman moves by only 0.010.
  3. In ranks, an extreme price can only move to the top or the bottom rank. Its distance from the other prices no longer counts, so its pull on Spearman is limited.

M27-C08 · Choose the typical value for each column

Section titled “M27-C08 · Choose the typical value for each column”
Core

Choose a method and justify: for six numeric columns of customers (age, tenure_months, monthly_charges, support_tickets, logins_last_30d, avg_session_minutes), print the skew, the mean, the median and which of the two you would report as “typical”. Use the rule from the lesson: report the median when the absolute skew is 0.5 or more.

Expected output
skew mean median report
age 0.16 42.26 42.00 mean
tenure_months 1.02 23.08 17.00 median
monthly_charges 0.62 60.84 58.86 median
support_tickets 1.04 1.24 1.00 median
logins_last_30d 1.72 11.74 10.00 median
avg_session_minutes 1.27 14.34 12.90 median
Starter
columns = ["age", "tenure_months", "monthly_charges",
"support_tickets", "logins_last_30d", "avg_session_minutes"]
# TODO: skew, mean and median of each column
# TODO: np.where(abs(skew) >= 0.5, "median", "mean")
Hint 1

customers[columns].skew() returns one skew per column. .mean() and .median() work the same way.

Hint 2

Put the three Series into one DataFrame, then add the report column with np.where.

Solution
columns = [
"age", "tenure_months", "monthly_charges",
"support_tickets", "logins_last_30d", "avg_session_minutes",
]
data = customers[columns]
table = pd.DataFrame(
{"skew": data.skew(), "mean": data.mean(), "median": data.median()}
)
table["report"] = np.where(table["skew"].abs() >= 0.5, "median", "mean")
print(table.round(2))
assert table.loc["age", "report"] == "mean"
assert (table["report"] == "median").sum() == 5
Output
skew mean median report
age 0.16 42.26 42.00 mean
tenure_months 1.02 23.08 17.00 median
monthly_charges 0.62 60.84 58.86 median
support_tickets 1.04 1.24 1.00 median
logins_last_30d 1.72 11.74 10.00 median
avg_session_minutes 1.27 14.34 12.90 median

How it works:

  1. Only age is close to symmetric (skew 0.16), so its mean is a fair “typical” value.
  2. The other five columns are right-skewed. Their means sit above their medians: the mean tenure is 23.08 months, the median 17.
  3. The 0.5 cut-off is a convention. The point is to look at the shape before you pick the center.

M27-C09 · Find where Pearson and Spearman disagree

Section titled “M27-C09 · Find where Pearson and Spearman disagree”
Core

Interpret a result: for every numeric column of houses (except price), compute Pearson and Spearman with price and the gap (Spearman minus Pearson). Print the three columns with the largest absolute gap. Then print the median price (in thousands) and the number of houses per school_rating to see the shape behind one of the gaps.

Expected output
pearson spearman gap
distance_to_center_km -0.143 -0.325 -0.181
school_rating 0.566 0.681 0.116
lot_sqft -0.082 -0.148 -0.066
median size
school_rating
1.0 218.0 4
2.0 253.5 33
3.0 241.8 148
4.0 267.2 308
5.0 299.0 493
6.0 336.5 473
7.0 407.0 539
8.0 537.2 404
9.0 651.5 325
10.0 773.0 183
Starter
numeric = houses.select_dtypes("number").drop(columns="price")
# TODO: corrwith(houses["price"]) for both methods
# TODO: gap column, sort by its absolute value, keep the top 3
# TODO: median price per school_rating
Hint 1

numeric.corrwith(houses["price"], method="spearman") correlates every column with the price in one call.

Hint 2

sort_values("gap", key=abs, ascending=False) ranks by the size of the gap and keeps its sign.

Solution
numeric = houses.select_dtypes("number").drop(columns="price")
table = pd.DataFrame(
{
"pearson": numeric.corrwith(houses["price"]),
"spearman": numeric.corrwith(houses["price"], method="spearman"),
}
)
table["gap"] = table["spearman"] - table["pearson"]
top = table.sort_values("gap", key=abs, ascending=False).head(3)
print(top.round(3))
by_rating = houses.groupby("school_rating")["price"].agg(median="median", size="size")
by_rating["median"] = by_rating["median"] / 1000
print(by_rating.round(1))
assert top.index[0] == "distance_to_center_km"
assert by_rating.loc[3:, "median"].is_monotonic_increasing
Output
pearson spearman gap
distance_to_center_km -0.143 -0.325 -0.181
school_rating 0.566 0.681 0.116
lot_sqft -0.082 -0.148 -0.066
median size
school_rating
1.0 218.0 4
2.0 253.5 33
3.0 241.8 148
4.0 267.2 308
5.0 299.0 493
6.0 336.5 473
7.0 407.0 539
8.0 537.2 404
9.0 651.5 325
10.0 773.0 183

How it works:

  1. corrwith computes one coefficient per column, so the two Series line up by column name.
  2. A large gap between the two coefficients is a flag: the relationship is curved, or a few extreme values pull on Pearson. It tells you which scatter plots to look at first.
  3. From rating 3 upward, the median price (in thousands) rises with every step, and the steps get bigger from rating 7. Ratings 1 and 2 have only 4 and 33 houses, so their medians are noisy. The relationship is monotonic but curved, and price is skewed, so Spearman is the higher of the two.
  4. For distance, the lesson’s pairplot shows a hump: the most expensive houses sit at middle distances. Neither coefficient describes a hump well; the gap only tells you to look.
Core

Fix the bug: a colleague’s script should list the three customer features most associated with churn. It has two bugs. It crashes, and once it runs, it ranks a strong negative association last. Fix both and print the three features with their Spearman correlation.

Expected output
tenure_months -0.336
total_charges -0.289
support_tickets 0.178
Name: churned, dtype: float64
Starter
corr = customers.corr(method="spearman")
top3 = corr["churned"].drop("churned").sort_values(ascending=False).head(3)
print(top3)
Hint 1

Run it. The error says pandas cannot convert a string such as 'C00001' to a float.

Hint 2

Pass numeric_only=True. Then sort with key=abs so that a correlation of −0.34 ranks above one of +0.18.

Solution
corr = customers.corr(method="spearman", numeric_only=True)
churn_corr = corr["churned"].drop("churned")
top3 = churn_corr.sort_values(key=abs, ascending=False).head(3)
print(top3.round(3))
assert top3.index[0] == "tenure_months"
assert (top3 < 0).sum() == 2
Output
tenure_months -0.336
total_charges -0.289
support_tickets 0.178
Name: churned, dtype: float64

How it works:

  1. pandas 3 does not skip text columns in corr() by default. numeric_only=True keeps only the numeric ones.
  2. Sorting the signed values puts the strongest negative correlations at the bottom. key=abs ranks by strength.
  3. Tenure and total charges (both negative) and support tickets (positive) lead. Total charges is mostly tenure in disguise: see M27-C12.

M27-C11 · Online share by region and year

Section titled “M27-C11 · Online share by region and year”
Core

For sales, build a table of the online share of order lines with region in the rows and the year (2023, 2024) in the columns. Add a column change (2024 minus 2023, in percentage points). Print it with three decimals, sorted by change.

Expected output
year 2023 2024 change
region
South 0.367 0.450 8.333
West 0.364 0.454 9.075
North 0.380 0.473 9.207
East 0.363 0.470 10.707
Starter
year = sales["order_date"].str[:4]
online = sales["channel"] == "online"
# TODO: group online by region and year, take the mean, unstack the year
# TODO: change column in percentage points
Hint 1

The mean of a boolean column is the share of True. online.groupby([sales["region"], year]).mean() gives one value per pair.

Hint 2

.unstack() moves the year level into the columns. Percentage points are (b - a) * 100.

Solution
year = sales["order_date"].str[:4].rename("year")
online = (sales["channel"] == "online").rename("online")
share = online.groupby([sales["region"], year]).mean().unstack()
share["change"] = (share["2024"] - share["2023"]) * 100
print(share.sort_values("change").round(3))
assert (share["change"] > 0).all()
assert share.shape == (4, 3)
Output
year 2023 2024 change
region
South 0.367 0.450 8.333
West 0.364 0.454 9.075
North 0.380 0.473 9.207
East 0.363 0.470 10.707

How it works:

  1. Grouping a Series by two other Series aligns them on the row index.
  2. unstack() turns the inner index level (the year) into columns.
  3. The online share rose in every region. A percentage point is the plain difference of two percentages: a change from 36% to 46% is +10 points, or +28% in relative terms.

M27-C12 · Scan for redundant features and leakage suspects

Section titled “M27-C12 · Scan for redundant features and leakage suspects”
Core

Interpret a result. (a) Find every pair of numeric customers features (without churned) with an absolute Spearman correlation above 0.8 and print it. (b) A colleague adds price_per_sqft = price / sqft to houses as a feature for a price model. Print its Spearman correlation with price, and decide whether a “|rho| > 0.9 means leakage” alarm would catch it.

Expected output
tenure_months total_charges 0.936
dtype: float64
rho(price_per_sqft, price) = 0.686; alarm fires: False
Starter
features = customers.select_dtypes("number").drop(columns="churned")
# TODO: (a) Spearman matrix, upper triangle, pairs with |rho| > 0.8
# TODO: (b) price_per_sqft and its correlation with price
Hint 1

Use the upper-triangle mask from the lesson: corr.where(np.triu(np.ones(corr.shape, dtype=bool), k=1)).stack().

Hint 2

For (b), think about how the column is built, not only about the number.

Solution
features = customers.select_dtypes("number").drop(columns="churned")
corr = features.corr(method="spearman")
pairs = corr.where(np.triu(np.ones(corr.shape, dtype=bool), k=1)).stack()
print(pairs[pairs.abs() > 0.8].round(3))
price_per_sqft = houses["price"] / houses["sqft"]
rho = price_per_sqft.corr(houses["price"], method="spearman")
print(f"rho(price_per_sqft, price) = {rho:.3f}; alarm fires: {abs(rho) > 0.9}")
assert len(pairs[pairs.abs() > 0.8]) == 1
assert abs(rho) < 0.9
Output
tenure_months total_charges 0.936
dtype: float64
rho(price_per_sqft, price) = 0.686; alarm fires: False

How it works:

  1. (a) Only tenure and total charges pass 0.8: total charges is roughly monthly charges × tenure. Keep one of them, or replace total charges by a ratio, so that a linear model does not split one effect between two columns.
  2. (b) price_per_sqft is computed from the target. It is pure leakage: at prediction time the price is unknown, so the column cannot exist.
  3. Its correlation (0.686) is far below the alarm. A correlation threshold does not detect leakage; only the question “how and when is this column made?” does.
Core

Find the weekday with the highest daily revenue in sales. First sum the revenue per day, then average the days by weekday name. Print the mean daily revenue per weekday (rounded to whole numbers) sorted from high to low, and the ratio of the best to the worst weekday.

Expected output
order_date
Saturday 6365.0
Sunday 5636.0
Friday 5598.0
Thursday 4416.0
Wednesday 4259.0
Monday 4233.0
Tuesday 3943.0
Name: revenue, dtype: float64
best / worst: 1.61
Starter
# TODO: daily = revenue summed per order_date
# TODO: weekday name of each date with pd.to_datetime(...).day_name()
# TODO: mean daily revenue per weekday, sorted
Hint 1

daily = sales.groupby("order_date")["revenue"].sum() gives one value per day (731 days).

Hint 2

pd.to_datetime(daily.index).day_name() gives the weekday of each day. Group daily by it.

Solution
daily = sales.groupby("order_date")["revenue"].sum()
weekday = pd.to_datetime(daily.index).day_name()
by_weekday = daily.groupby(weekday).mean().sort_values(ascending=False)
print(by_weekday.round(0))
print(f"best / worst: {by_weekday.iloc[0] / by_weekday.iloc[-1]:.2f}")
assert by_weekday.index[0] == "Saturday"
assert len(daily) == 731
Output
order_date
Saturday 6365.0
Sunday 5636.0
Friday 5598.0
Thursday 4416.0
Wednesday 4259.0
Monday 4233.0
Tuesday 3943.0
Name: revenue, dtype: float64
best / worst: 1.61

How it works:

  1. The unit of analysis is the thing that one row represents. The question is about days, so the first step turns order lines into days.
  2. Each weekday then has 104 or 105 days, and the mean compares like with like.
  3. Saturday brings about 1.6 times the revenue of Tuesday. A mean revenue per line by weekday would answer a different question (the size of a typical line), not “which day is busiest”.

M27-X01 · Build a Simpson’s paradox detector

Section titled “M27-X01 · Build a Simpson’s paradox detector”
Challenge

Write simpson_check(df, x, y, group) that returns the overall Spearman correlation of x and y, the correlation inside each group, and a verdict: "reverses" when every group has the opposite sign of the overall value, "vanishes" when every group’s absolute value is less than half the overall absolute value, and "holds" otherwise. Drop rows with a missing x or y first. Run it on houses for sqft, lot_sqft and distance_to_center_km against price, grouped by neighborhood. Print one line per feature with the overall value, the range of the group values and the verdict.

Expected output
sqft overall +0.679 groups +0.533..+0.870 holds
lot_sqft overall -0.148 groups +0.026..+0.110 reverses
distance_to_center_km overall -0.325 groups -0.032..+0.147 vanishes
Starter
def simpson_check(df: pd.DataFrame, x: str, y: str, group: str):
# TODO: drop rows with missing x or y
# TODO: overall Spearman, then Spearman per group
# TODO: verdict
...
for feature in ["sqft", "lot_sqft", "distance_to_center_km"]:
... # TODO: call and print
Hint 1

The per-group values come from data.groupby(group)[[x, y]].apply(lambda g: g[x].corr(g[y], method="spearman")).

Hint 2

“Every group has the opposite sign” is (np.sign(within) == -np.sign(overall)).all().

Hint 3

Return a tuple (overall, within, verdict) and unpack it in the loop.

Solution
def simpson_check(
df: pd.DataFrame, x: str, y: str, group: str
) -> tuple[float, pd.Series, str]:
"""Compare an overall Spearman correlation with the one inside each group."""
data = df.dropna(subset=[x, y])
overall = data[x].corr(data[y], method="spearman")
within = data.groupby(group)[[x, y]].apply(
lambda g: g[x].corr(g[y], method="spearman")
)
if (np.sign(within) == -np.sign(overall)).all():
verdict = "reverses"
elif (within.abs() < abs(overall) / 2).all():
verdict = "vanishes"
else:
verdict = "holds"
return overall, within, verdict
results = {}
for feature in ["sqft", "lot_sqft", "distance_to_center_km"]:
overall, within, verdict = simpson_check(houses, feature, "price", "neighborhood")
results[feature] = verdict
print(
f"{feature:<22} overall {overall:+.3f} "
f"groups {within.min():+.3f}..{within.max():+.3f} {verdict}"
)
assert results == {
"sqft": "holds",
"lot_sqft": "reverses",
"distance_to_center_km": "vanishes",
}
Output
sqft overall +0.679 groups +0.533..+0.870 holds
lot_sqft overall -0.148 groups +0.026..+0.110 reverses
distance_to_center_km overall -0.325 groups -0.032..+0.147 vanishes

How it works:

  1. Size holds: its correlation is strong overall and inside every neighborhood.
  2. Lot size reverses: negative overall, positive in all 8 neighborhoods. The neighborhood confounds it (Simpson’s paradox).
  3. Distance vanishes: −0.325 overall, close to 0 inside each neighborhood. The “distance effect” is really a difference between neighborhoods. Within one area, a house 2 km further out costs about the same.

M27-X02 · Estimate the pool premium like with like

Section titled “M27-X02 · Estimate the pool premium like with like”
Challenge

The raw median price of pool houses is far above that of other houses. Estimate a fairer premium: per neighborhood, compare the median price per square foot of pool and non-pool houses, then average these gaps weighted by the number of pool houses in each neighborhood. Print the raw gap, the per-neighborhood table (gap and number of pool houses) and the weighted gap. Finish with one finding in the claim, evidence, caveat form.

Expected output
raw median gap: +78.1%
gap pools
neighborhood
Oak Hill 0.123 96
Lakeview 0.070 92
Maple Grove 0.047 47
Riverside 0.054 39
Cedar Park 0.090 25
Westfield -0.140 18
Downtown 0.067 7
Old Town 0.248 3
weighted per-sqft gap: +7.2%
Claim: A pool goes with a modest price premium, not a large one.
Evidence: +7.2% per sqft within neighborhoods (weighted by 327 pool houses) vs +78.1% raw.
Caveat: Observational; pool houses may also be newer or in better shape.
Starter
houses["price_per_sqft"] = houses["price"] / houses["sqft"]
# TODO: raw gap of median price, pool vs no pool
# TODO: per neighborhood: median price_per_sqft by has_pool, gap, pool count
# TODO: weighted mean of the gaps (np.average with weights=...)
# TODO: print the finding
Hint 1

houses.pivot_table(index="neighborhood", columns="has_pool", values="price_per_sqft", aggfunc="median") gives the two medians per neighborhood.

Hint 2

The pool count per neighborhood is houses.groupby("neighborhood")["has_pool"].sum().

Hint 3

np.average(table["gap"], weights=table["pools"]) weights each gap by its number of pool houses.

Solution
houses["price_per_sqft"] = houses["price"] / houses["sqft"]
medians = houses.groupby("has_pool")["price"].median()
raw_gap = medians[1] / medians[0] - 1
per_area = houses.pivot_table(
index="neighborhood", columns="has_pool", values="price_per_sqft", aggfunc="median"
)
table = pd.DataFrame(
{
"gap": per_area[1] / per_area[0] - 1,
"pools": houses.groupby("neighborhood")["has_pool"].sum(),
}
)
weighted_gap = np.average(table["gap"], weights=table["pools"])
print(f"raw median gap: {raw_gap:+.1%}")
print(table.sort_values("pools", ascending=False).round(3))
print(f"weighted per-sqft gap: {weighted_gap:+.1%}")
print("Claim: A pool goes with a modest price premium, not a large one.")
print(
f"Evidence: {weighted_gap:+.1%} per sqft within neighborhoods "
f"(weighted by {table['pools'].sum()} pool houses) vs {raw_gap:+.1%} raw."
)
print("Caveat: Observational; pool houses may also be newer or in better shape.")
assert weighted_gap < raw_gap / 5
assert table["pools"].sum() == houses["has_pool"].sum()
Output
raw median gap: +78.1%
gap pools
neighborhood
Oak Hill 0.123 96
Lakeview 0.070 92
Maple Grove 0.047 47
Riverside 0.054 39
Cedar Park 0.090 25
Westfield -0.140 18
Downtown 0.067 7
Old Town 0.248 3
weighted per-sqft gap: +7.2%
Claim: A pool goes with a modest price premium, not a large one.
Evidence: +7.2% per sqft within neighborhoods (weighted by 327 pool houses) vs +78.1% raw.
Caveat: Observational; pool houses may also be newer or in better shape.

How it works:

  1. The raw gap mixes three things: pools, bigger houses and pricier neighborhoods.
  2. Price per square foot removes the size effect. Comparing inside each neighborhood removes the location effect.
  3. Weighting by pool count stops Old Town (3 pool houses) from moving the average as much as Lakeview (92). The fair premium is under a fifth of the raw gap.

Alternative: a regression with neighborhood dummies and log(sqft) estimates the same premium in one model. Module 35 builds it.

Challenge

Write checklist(df, key, target=None) that returns a dict with: rows, columns, dtypes (a dict of dtype name → count), missing (dict of column → count, only columns with gaps), duplicate_rows, key_unique, and, when target is given, target_share (share of the most frequent value, rounded to 3) or, for a target with more than 10 values, target_skew (rounded to 2). Print the result for customers (key customer_id, target churned) and for houses (key house_id, target price), one name: value line per entry.

Expected output
== customers
rows: 5000
columns: 15
dtypes: {'str': 6, 'int64': 6, 'float64': 3}
missing: {'total_charges': 10}
duplicate_rows: 0
key_unique: True
target_share: 0.807
== houses
rows: 3000
columns: 14
dtypes: {'int64': 7, 'float64': 4, 'str': 3}
missing: {'lot_sqft': 90, 'school_rating': 90}
duplicate_rows: 0
key_unique: True
target_skew: 2.67
Starter
def checklist(df: pd.DataFrame, key: str, target: str | None = None) -> dict:
report = {"rows": len(df), "columns": df.shape[1]}
# TODO: dtypes, missing, duplicate_rows, key_unique
# TODO: target_share or target_skew
return report
# TODO: run it on both tables and print each entry
Hint 1

df.dtypes.astype(str).value_counts().to_dict() gives the dtype counts as plain strings.

Hint 2

df[target].nunique() > 10 separates a numeric target from a class label.

Solution
def checklist(df: pd.DataFrame, key: str, target: str | None = None) -> dict:
"""Run checks 1-3 and 6 of the EDA checklist and return the findings."""
missing = df.isna().sum()
report = {
"rows": len(df),
"columns": df.shape[1],
"dtypes": df.dtypes.astype(str).value_counts().to_dict(),
"missing": missing[missing > 0].to_dict(),
"duplicate_rows": int(df.duplicated().sum()),
"key_unique": bool(df[key].is_unique),
}
if target is not None:
if df[target].nunique() > 10:
report["target_skew"] = round(float(df[target].skew()), 2)
else:
top_share = df[target].value_counts(normalize=True).iloc[0]
report["target_share"] = round(float(top_share), 3)
return report
for name, df, key, target in [
("customers", customers, "customer_id", "churned"),
("houses", houses, "house_id", "price"),
]:
print(f"== {name}")
report = checklist(df, key, target)
for entry, value in report.items():
print(f"{entry}: {value}")
assert checklist(customers, "customer_id", "churned")["target_share"] == 0.807
assert checklist(houses, "house_id", "price")["missing"]["lot_sqft"] == 90
Output
== customers
rows: 5000
columns: 15
dtypes: {'str': 6, 'int64': 6, 'float64': 3}
missing: {'total_charges': 10}
duplicate_rows: 0
key_unique: True
target_share: 0.807
== houses
rows: 3000
columns: 14
dtypes: {'int64': 7, 'float64': 4, 'str': 3}
missing: {'lot_sqft': 90, 'school_rating': 90}
duplicate_rows: 0
key_unique: True
target_skew: 2.67

How it works:

  1. Each check is one pandas expression. int(), bool() and float() turn NumPy scalars into plain Python values, so the dict prints cleanly.
  2. The target branch picks the right summary: the share of the larger class for a label, the skew for a continuous value.
  3. The output is a checklist that you can run on every new table, and later turn into automated data-quality tests (module 14).

M27-X04 · Write a findings report for the sales team

Section titled “M27-X04 · Write a findings report for the sales team”
Challenge

Compute the evidence and print a three-finding report for sales, each as claim, evidence and caveat: (1) Electronics’ share of revenue against its share of lines; (2) the online share of lines in 2023 and in 2024; (3) the mean daily revenue on Saturdays against Tuesdays. Test finding 3 before you print it: does the same weekday lead when you use the median daily revenue, and when you leave out November and December (the promo season)? Put the result in the caveat. Every number must come from the code.

Expected output
1. Electronics brings in half of the revenue.
Evidence: 50.3% of revenue from 19.5% of lines (2023-2024).
Caveat: High prices, not volume; a few TV and laptop lines move the total.
2. Sales lines are moving online.
Evidence: Online share of lines 36.8% (2023) -> 46.2% (2024).
Caveat: Two years only; stores fulfill online orders, so store workload stays.
3. Saturday is the busiest day.
Evidence: Mean daily revenue 6,365 on Saturdays vs 3,943 on Tuesdays.
Caveat: Top day by median: Saturday; without Nov-Dec: Saturday.
Starter
# TODO: line and revenue share of Electronics
# TODO: online share per year
# TODO: mean daily revenue per weekday, plus the median and a mean without Nov-Dec
# TODO: build a list of (claim, evidence, caveat) and print it
Hint 1

Reuse the patterns of M27-W06 (shares), M27-C11 (online share per year) and M27-C13 (daily revenue per weekday).

Hint 2

Build each evidence string with an f-string. Format shares with :.1% and money with :,.0f.

Solution
is_electronics = sales["category"] == "Electronics"
line_share = is_electronics.mean()
revenue_share = sales.loc[is_electronics, "revenue"].sum() / sales["revenue"].sum()
year = sales["order_date"].str[:4]
online_by_year = (sales["channel"] == "online").groupby(year).mean()
daily = sales.groupby("order_date")["revenue"].sum()
dates = pd.to_datetime(daily.index)
by_weekday = daily.groupby(dates.day_name()).mean()
median_by_weekday = daily.groupby(dates.day_name()).median()
outside_peak = ~dates.month.isin([11, 12])
calm_by_weekday = daily[outside_peak].groupby(dates[outside_peak].day_name()).mean()
findings = [
(
"Electronics brings in half of the revenue.",
f"{revenue_share:.1%} of revenue from {line_share:.1%} of lines (2023-2024).",
"High prices, not volume; a few TV and laptop lines move the total.",
),
(
"Sales lines are moving online.",
f"Online share of lines {online_by_year['2023']:.1%} (2023) -> "
f"{online_by_year['2024']:.1%} (2024).",
"Two years only; stores fulfill online orders, so store workload stays.",
),
(
"Saturday is the busiest day.",
f"Mean daily revenue {by_weekday['Saturday']:,.0f} on Saturdays vs "
f"{by_weekday['Tuesday']:,.0f} on Tuesdays.",
f"Top day by median: {median_by_weekday.idxmax()}; "
f"without Nov-Dec: {calm_by_weekday.idxmax()}.",
),
]
for number, (claim, evidence, caveat) in enumerate(findings, start=1):
print(f"{number}. {claim}\n Evidence: {evidence}\n Caveat: {caveat}")
assert revenue_share > 2 * line_share
assert online_by_year["2024"] > online_by_year["2023"]
assert median_by_weekday.idxmax() == calm_by_weekday.idxmax() == "Saturday"
Output
1. Electronics brings in half of the revenue.
Evidence: 50.3% of revenue from 19.5% of lines (2023-2024).
Caveat: High prices, not volume; a few TV and laptop lines move the total.
2. Sales lines are moving online.
Evidence: Online share of lines 36.8% (2023) -> 46.2% (2024).
Caveat: Two years only; stores fulfill online orders, so store workload stays.
3. Saturday is the busiest day.
Evidence: Mean daily revenue 6,365 on Saturdays vs 3,943 on Tuesdays.
Caveat: Top day by median: Saturday; without Nov-Dec: Saturday.

How it works:

  1. Each block of code computes the evidence for one finding. Nothing is typed by hand.
  2. The evidence lines name the time window and the unit (lines, days), so a reader can check them.
  3. Each caveat names the most likely way the claim could mislead: price effects, a short time window, promo days.
  4. Finding 3 is tested before it is printed. The median resists the few huge promo days, and dropping November and December removes the promo season. Saturday leads in both checks, so the caveat can say so.

M27-X05 · Refactor churn exploration into a class

Section titled “M27-X05 · Refactor churn exploration into a class”
Challenge

Refactor: three functions repeat the same groupby code. Turn them into a class ChurnExplorer that stores the table and the target once, with methods rate_by(column), rate_by_bins(column, bins) and top_segments(columns, min_size). Each rate table has the columns rate, size and lift. top_segments returns the three segments with the highest rate among those with at least min_size customers. Print rate_by("contract"), rate_by_bins("age", [17, 35, 55, 80]) and top_segments(["contract", "payment_method"], 100).

Expected output
rate size lift
contract
month-to-month 0.296 2784 1.535
one-year 0.088 1225 0.458
two-year 0.032 991 0.168
rate size lift
age
(17, 35] 0.249 1546 1.293
(35, 55] 0.148 2683 0.768
(55, 80] 0.235 771 1.219
rate size lift
contract payment_method
month-to-month electronic_check 0.370 873 1.921
bank_transfer 0.273 656 1.417
paypal 0.265 502 1.376
Starter
def churn_by(df, column):
return df.groupby(column)["churned"].mean()
def churn_by_bins(df, column, bins):
return df.groupby(pd.cut(df[column], bins), observed=True)["churned"].mean()
def churn_by_two(df, a, b):
return df.groupby([a, b])["churned"].mean()
# TODO: class ChurnExplorer with rate_by, rate_by_bins, top_segments
Hint 1

Put the shared code in one private method _rates(self, keys) that takes anything groupby accepts and returns rate, size and lift.

Hint 2

Compute the base rate once in __init__: self.base_rate = df[target].mean().

Hint 3

In top_segments, filter with table[table["size"] >= min_size], then nlargest(3, "rate").

Solution
class ChurnExplorer:
"""Churn rates, sizes and lifts for any grouping of a customer table."""
def __init__(self, df: pd.DataFrame, target: str = "churned") -> None:
self.df = df
self.target = target
self.base_rate = df[target].mean()
def _rates(self, keys) -> pd.DataFrame:
grouped = self.df.groupby(keys, observed=True)[self.target]
table = grouped.agg(rate="mean", size="size")
table["lift"] = table["rate"] / self.base_rate
return table.round(3)
def rate_by(self, column: str) -> pd.DataFrame:
return self._rates(column)
def rate_by_bins(self, column: str, bins: list[float]) -> pd.DataFrame:
return self._rates(pd.cut(self.df[column], bins))
def top_segments(self, columns: list[str], min_size: int) -> pd.DataFrame:
table = self._rates(columns)
return table[table["size"] >= min_size].nlargest(3, "rate")
explorer = ChurnExplorer(customers)
print(explorer.rate_by("contract"))
print(explorer.rate_by_bins("age", [17, 35, 55, 80]))
top = explorer.top_segments(["contract", "payment_method"], 100)
print(top)
assert top.index[0] == ("month-to-month", "electronic_check")
assert (top["size"] >= 100).all()
Output
rate size lift
contract
month-to-month 0.296 2784 1.535
one-year 0.088 1225 0.458
two-year 0.032 991 0.168
rate size lift
age
(17, 35] 0.249 1546 1.293
(35, 55] 0.148 2683 0.768
(55, 80] 0.235 771 1.219
rate size lift
contract payment_method
month-to-month electronic_check 0.370 873 1.921
bank_transfer 0.273 656 1.417
paypal 0.265 502 1.376

How it works:

  1. _rates holds the only groupby. The three public methods differ only in the keys they pass: a column name, a pd.cut result or a list of columns.
  2. The base rate is computed once and reused for every lift.
  3. The class keeps the table and the target together, so a caller cannot mix the rate of one table with the base rate of another. min_size builds the “check the group size” rule into the method.

M27-X06 · Report a rate by a count column with small groups merged

Section titled “M27-X06 · Report a rate by a count column with small groups merged”
Challenge

Churn by support_tickets has groups with a single customer. Merge 5 or more tickets into one group 5+, then print the rate, size and lift per group, with the groups in order 0, 1, 2, 3, 4, 5+. Mark every group with fewer than 50 customers as small in a note column (empty string otherwise). Print the table, then one sentence on the trend.

Expected output
rate size lift note
0 0.132 1537 0.686
1 0.160 1742 0.832
2 0.207 1027 1.077
3 0.326 457 1.693
4 0.473 184 2.455
5+ 0.604 53 3.135
Churn rises with every ticket, from 13.2% to 60.4% at 5+ tickets.
Starter
tickets = customers["support_tickets"]
# TODO: group labels "0".."4" and "5+"
# TODO: rate, size and lift per group, in the right order
# TODO: note column for small groups
Hint 1

tickets.clip(upper=5) turns every value above 5 into 5. Then map 5 to "5+".

Hint 2

An ordered categorical makes the order of the labels explicit: pd.Categorical(labels, categories=[...], ordered=True).

Solution
tickets = customers["support_tickets"]
order = ["0", "1", "2", "3", "4", "5+"]
labels = tickets.clip(upper=5).astype(str).replace("5", "5+")
group = pd.Categorical(labels, categories=order, ordered=True)
grouped = customers.groupby(group, observed=True)["churned"]
table = grouped.agg(rate="mean", size="size")
table["lift"] = table["rate"] / customers["churned"].mean()
table["note"] = np.where(table["size"] < 50, "small", "")
print(table.round(3))
first, last = table["rate"].iloc[0], table["rate"].iloc[-1]
print(f"Churn rises with every ticket, from {first:.1%} to {last:.1%} at 5+ tickets.")
assert table["rate"].is_monotonic_increasing
assert table.loc["5+", "size"] == (tickets >= 5).sum()
Output
rate size lift note
0 0.132 1537 0.686
1 0.160 1742 0.832
2 0.207 1027 1.077
3 0.326 457 1.693
4 0.473 184 2.455
5+ 0.604 53 3.135
Churn rises with every ticket, from 13.2% to 60.4% at 5+ tickets.

How it works:

  1. clip(upper=5) caps the counts, so 5 to 9 tickets become one group of 53 customers.
  2. The ordered categorical keeps 0 to 5+ in their natural order in the output.
  3. After merging, the trend is clean and monotonic. The 5+ group is now large enough to report, and the note column would flag any group that is still small.