Skip to content

29. Statistics and probability — Exercises

These exercises practice every idea of the Statistics and probability lesson. They use the course datasets: customers.csv, houses.csv, ab_test.csv and sales.csv (see the data dictionary).

How to work:

  1. Read the task and the expected output.
  2. Put the setup block below at the top of your script (for example exercise.py). Then copy the starter code under it and replace each to-do comment with your code.
  3. Run the script with python exercise.py from your project folder. 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. Many exercises also ask you to interpret a number in one or two sentences. Write the sentences down; a statistic without an interpretation is half an answer.

Every exercise runs after this block:

import numpy as np
import pandas as pd
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)
customers = pd.read_csv("data/customers.csv")
houses = pd.read_csv("data/houses.csv")
ab = pd.read_csv("data/ab_test.csv")
sales = pd.read_csv("data/sales.csv")

M29-W01 · Mean, median and one bulk order

Section titled “M29-W01 · Mean, median and one bulk order”
Warm-up

A small shop records its revenue for seven days: 412.5, 398.0, 455.25, 430.0, 389.75, 441.0, 4120.0. The last day had one bulk order. Print the mean and the median of all seven days, then of the six normal days. Which statistic would you report as a “typical day”?

Expected output
all days: mean 949.50 | median 430.00
normal days: mean 421.08 | median 421.25
Starter
daily = pd.Series([412.5, 398.0, 455.25, 430.0, 389.75, 441.0, 4120.0])
# TODO: print the mean and the median of all seven days
# TODO: keep the days below 1000 and print their mean and median
Hint 1

daily.mean() and daily.median() give the two statistics. Format them with :.2f.

Hint 2

A boolean mask keeps the normal days: normal = daily[daily < 1000].

Solution
daily = pd.Series([412.5, 398.0, 455.25, 430.0, 389.75, 441.0, 4120.0])
print(f"all days: mean {daily.mean():.2f} | median {daily.median():.2f}")
normal = daily[daily < 1000]
print(f"normal days: mean {normal.mean():.2f} | median {normal.median():.2f}")
assert daily.median() == 430.0
assert daily.mean() > 2 * normal.mean()
Output
all days: mean 949.50 | median 430.00
normal days: mean 421.08 | median 421.25

How it works:

  1. One bulk day more than doubles the mean, from about 421 to about 949 USD.
  2. The median moves only from 421.25 to 430.0, because it depends on the order of the values, not on how large the largest value is.
  3. Report the median as the typical day. Report the mean (or the total) when you plan cash flow, because the bulk order is real money.

Alternative: a trimmed mean drops a share of the smallest and largest values before it averages. stats.trim_mean(daily, 0.15) cuts 15% at each end (one value of seven) and gives a robust compromise between the mean and the median.

daily = pd.Series([412.5, 398.0, 455.25, 430.0, 389.75, 441.0, 4120.0])
print(round(stats.trim_mean(daily, 0.15), 2))
Output
427.35
Warm-up

Predict the output: write down what each line prints, then run the code. The values are four readings: 2, 4, 6 and 8.

Acceptance criteria:

  • Write your prediction for every line before you run the code.
  • Your prediction matches the Output in the solution, line by line (to 4 decimals).
  • You can say which lines divide by nn and which by n−1n - 1.
Starter
x = np.array([2.0, 4.0, 6.0, 8.0])
print(np.var(x))
print(np.var(x, ddof=1))
print(round(pd.Series(x).var(), 4))
print(round(pd.Series(x).std(ddof=0), 4))
print(round(np.std(x, ddof=1), 4))
# TODO: write your prediction for each line before you run it
Hint 1

The mean is 5. The squared deviations are 9, 1, 1 and 9. Their sum is 20.

Hint 2

NumPy divides by n−ddofn - \text{ddof} with ddof=0 by default. pandas uses ddof=1 by default. The standard deviation is the square root of the variance.

Solution
x = np.array([2.0, 4.0, 6.0, 8.0])
print(np.var(x))
print(np.var(x, ddof=1))
print(round(pd.Series(x).var(), 4))
print(round(pd.Series(x).std(ddof=0), 4))
print(round(np.std(x, ddof=1), 4))
assert np.var(x) == 20 / 4
assert np.isclose(pd.Series(x).var(), 20 / 3)
Output
5.0
6.666666666666667
6.6667
2.2361
2.582

How it works:

  1. np.var(x) divides the sum of squares, 20, by n=4n = 4: 5.0.
  2. ddof=1 divides by n−1=3n - 1 = 3: 6.667. pandas var() uses ddof=1 by default, so it agrees.
  3. std(ddof=0) is 5=2.2361\sqrt{5} = 2.2361; np.std(x, ddof=1) is 6.667=2.582\sqrt{6.667} = 2.582.

Alternative: the standard library’s statistics.variance is the sample variance (ddof=1) and statistics.pvariance is the population variance (ddof=0). Their names make the choice explicit.

Warm-up

Compute the first quartile, the third quartile and the IQR of monthly_charges in customers. Compute the upper fence Q3+1.5 IQRQ_3 + 1.5\,\text{IQR} and count the customers above it. Then show how those customers split by plan.

Expected output
Q1 39.96 | Q3 72.00 | IQR 32.04 | upper fence 120.07
customers above the fence: 17
{'premium': 17}
Starter
charges = customers["monthly_charges"]
# TODO: q1, q3 and iqr with quantile()
# TODO: the upper fence and the customers above it
# TODO: value_counts of plan for those customers
Hint 1

q1, q3 = charges.quantile([0.25, 0.75]) unpacks the two quartiles.

Hint 2

customers.loc[charges > fence, "plan"].value_counts() counts the plans of the high payers.

Solution
charges = customers["monthly_charges"]
q1, q3 = charges.quantile([0.25, 0.75])
iqr = q3 - q1
fence = q3 + 1.5 * iqr
high = customers.loc[charges > fence, "plan"]
print(f"Q1 {q1:.2f} | Q3 {q3:.2f} | IQR {iqr:.2f} | upper fence {fence:.2f}")
print(f"customers above the fence: {len(high)}")
print(high.value_counts().to_dict())
assert np.isclose(iqr, stats.iqr(charges))
assert (customers.loc[charges > fence, "monthly_charges"] > fence).all()
Output
Q1 39.96 | Q3 72.00 | IQR 32.04 | upper fence 120.07
customers above the fence: 17
{'premium': 17}

How it works:

  1. quantile([0.25, 0.75]) returns two values; tuple unpacking names them.
  2. The fence rule from module 26 flags values far above the middle half of the data.
  3. All flagged customers are on the premium plan: they are not data errors but a separate group with a higher price. An “outlier” by the IQR rule is a value to look at, not a value to delete.

Alternative: stats.iqr(charges) computes the IQR in one call. Compute the fences per plan with groupby("plan") to find customers who are unusual within their plan.

M29-W04 · Sensor probabilities with the normal distribution

Section titled “M29-W04 · Sensor probabilities with the normal distribution”
Warm-up

A server-room sensor reads the true temperature of 21.0 °C plus normal noise with a standard deviation of 0.5 °C. Use a frozen stats.norm to print: the probability of a reading below 20.5 °C, the probability of a reading between 20.5 and 21.5 °C, the 99.5th percentile, and three simulated readings with random_state=42.

Expected output
P(< 20.5) = 0.1587
P(20.5 to 21.5) = 0.6827
99.5th percentile = 22.288
simulated: [21.25 20.93 21.32]
Starter
reading = stats.norm(loc=21.0, scale=0.5)
# TODO: P(reading < 20.5) with cdf
# TODO: P(20.5 <= reading <= 21.5) as a difference of two cdf values
# TODO: the 99.5th percentile with ppf
# TODO: three readings with rvs(size=3, random_state=42)
Hint 1

cdf(x) is the probability of a value at most x. For a continuous distribution, “below” and “at most” are the same.

Hint 2

The probability of a range is cdf(high) - cdf(low). The percentile is ppf(0.995).

Solution
reading = stats.norm(loc=21.0, scale=0.5)
below = reading.cdf(20.5)
between = reading.cdf(21.5) - reading.cdf(20.5)
p995 = reading.ppf(0.995)
print(f"P(< 20.5) = {below:.4f}")
print(f"P(20.5 to 21.5) = {between:.4f}")
print(f"99.5th percentile = {p995:.3f}")
print("simulated:", reading.rvs(size=3, random_state=42).round(2))
assert abs(between - 0.6827) < 1e-4 # the 68% rule: within 1 sd
assert np.isclose(reading.cdf(p995), 0.995)
Output
P(< 20.5) = 0.1587
P(20.5 to 21.5) = 0.6827
99.5th percentile = 22.288
simulated: [21.25 20.93 21.32]

How it works:

  1. 20.5 is one standard deviation below the mean, so about 16% of readings fall below it.
  2. The range from −1 to +1 standard deviation holds 68.27% of a normal distribution.
  3. ppf inverts cdf: the assert checks that the CDF at the 99.5th percentile is 0.995. An alert threshold at 22.29 °C fires on about 1 reading in 200 when nothing is wrong.

Alternative: standardize by hand with z-scores and use the standard normal: stats.norm.cdf((20.5 - 21.0) / 0.5) gives the same 0.1587.

M29-W05 · Binomial: churners in a new cohort

Section titled “M29-W05 · Binomial: churners in a new cohort”
Warm-up

The overall churn rate is 19.3%. A cohort of 50 new customers starts this month. Assume each one churns independently with probability 0.193. Print the expected number of churners, the probability of exactly 10 churners, the probability of 15 or more, and the central 90% range of the count.

Expected output
expected churners: 9.65
P(exactly 10) = 0.1387
P(15 or more) = 0.0464
90% of cohorts: 5 to 14 churners
Starter
cohort = stats.binom(n=50, p=0.193)
# TODO: expected churners with mean()
# TODO: P(exactly 10) with pmf
# TODO: P(15 or more) with sf
# TODO: the central 90% range with interval(0.90)
Hint 1

For a discrete count, “15 or more” is “more than 14”: cohort.sf(14).

Hint 2

interval(0.90) returns a tuple (low, high).

Solution
cohort = stats.binom(n=50, p=0.193)
low, high = cohort.interval(0.90)
print(f"expected churners: {cohort.mean():.2f}")
print(f"P(exactly 10) = {cohort.pmf(10):.4f}")
print(f"P(15 or more) = {cohort.sf(14):.4f}")
print(f"90% of cohorts: {low:.0f} to {high:.0f} churners")
assert np.isclose(cohort.sf(14), 1 - cohort.cdf(14))
assert np.isclose(cohort.mean(), 50 * 0.193)
Output
expected churners: 9.65
P(exactly 10) = 0.1387
P(15 or more) = 0.0464
90% of cohorts: 5 to 14 churners

How it works:

  1. The mean of a binomial is np=50×0.193=9.65np = 50 \times 0.193 = 9.65.
  2. pmf(10) is the probability of exactly 10. sf(14) is P(X>14)=P(X≥15)P(X > 14) = P(X \ge 15).
  3. Even with no change in the true rate, 90% of cohorts of 50 show between 5 and 14 churners, and the other 10% fall outside that range. A manager who panics at 14 churners is reacting to noise.

Alternative: simulate. cohort.rvs(size=100_000, random_state=42) gives 100,000 cohorts; (draws >= 15).mean() approximates the same probability.

M29-W06 · Poisson: support tickets per hour

Section titled “M29-W06 · Poisson: support tickets per hour”
Warm-up

The help desk receives on average 3 tickets per hour, at random times. With a Poisson model, print the probability of a quiet hour (0 tickets), the probability of 6 or more tickets, the number of tickets that is exceeded in only 1% of hours, and the probability that an 8-hour shift has at least one hour with 6 or more tickets (assume that hours are independent).

Expected output
P(0 tickets) = 0.0498
P(6 or more) = 0.0839
99th percentile: 8 tickets
P(more than 8) = 0.0038
P(at least one hour with 6+ in an 8-hour shift) = 0.504
Starter
tickets = stats.poisson(mu=3)
# TODO: P(0) with pmf
# TODO: P(6 or more) with sf
# TODO: the 99th percentile with ppf
# TODO: P(at least one hour with 6+ in 8 hours) = 1 - (1 - P(6+)) ** 8
Hint 1

“6 or more” is sf(5).

Hint 2

ppf(0.99) returns the smallest count k with cdf(k) >= 0.99.

Solution
tickets = stats.poisson(mu=3)
p99 = tickets.ppf(0.99)
print(f"P(0 tickets) = {tickets.pmf(0):.4f}")
print(f"P(6 or more) = {tickets.sf(5):.4f}")
print(f"99th percentile: {p99:.0f} tickets")
print(f"P(more than {p99:.0f}) = {tickets.sf(p99):.4f}")
assert np.isclose(tickets.pmf(0), np.exp(-3))
busy_shift = 1 - (1 - tickets.sf(5)) ** 8 # at least one busy hour in 8
print(f"P(at least one hour with 6+ in an 8-hour shift) = {busy_shift:.3f}")
assert tickets.cdf(p99) >= 0.99 > tickets.cdf(p99 - 1)
Output
P(0 tickets) = 0.0498
P(6 or more) = 0.0839
99th percentile: 8 tickets
P(more than 8) = 0.0038
P(at least one hour with 6+ in an 8-hour shift) = 0.504

How it works:

  1. P(X=0)=e−λ=e−3≈0.05P(X = 0) = e^{-\lambda} = e^{-3} \approx 0.05: about one hour in twenty is quiet.
  2. Six or more tickets arrive in about 8% of hours. If hours are independent, the chance that an 8-hour shift has at least one such hour is 1−(1−0.0839)8≈0.501 - (1 - 0.0839)^8 \approx 0.50. A staffing plan for “at most 5 per hour” is overrun on about half of the days.
  3. For a discrete distribution, ppf returns a whole count. The fourth line checks the tail: more than 8 tickets happens in less than 1% of hours.

Alternative: check the model on real data before you staff by it. The lesson found that daily orders are overdispersed (variance five times the mean). Count tickets per hour for a few weeks and compare counts.var() with counts.mean().

M29-W07 · Fix the bug: the critical value

Section titled “M29-W07 · Fix the bug: the critical value”
Warm-up

Fix the bug: an analyst builds a 95% confidence interval for the mean session length of 12 customers. The interval is too narrow. Find the two mistakes in the critical value and fix them.

Expected output
critical value 2.201 (was 1.645)
95% CI: 10.52 to 17.56
Starter
minutes = np.array(
[12.4, 8.1, 15.0, 22.3, 9.7, 11.2, 18.6, 7.5, 14.1, 10.9, 25.4, 13.3]
)
n = len(minutes)
se = minutes.std(ddof=1) / np.sqrt(n)
crit = stats.norm.ppf(0.95) # TODO: two mistakes on this line
print(f"95% CI: {minutes.mean() - crit * se:.2f} to {minutes.mean() + crit * se:.2f}")
Hint 1

A two-sided 95% interval leaves 2.5% in each tail. Which quantile is that?

Hint 2

With 12 values and an estimated standard deviation, the critical value comes from the t distribution with n−1n - 1 degrees of freedom.

Solution
minutes = np.array(
[12.4, 8.1, 15.0, 22.3, 9.7, 11.2, 18.6, 7.5, 14.1, 10.9, 25.4, 13.3]
)
n = len(minutes)
se = minutes.std(ddof=1) / np.sqrt(n)
crit = stats.t.ppf(0.975, df=n - 1)
low, high = minutes.mean() - crit * se, minutes.mean() + crit * se
print(f"critical value {crit:.3f} (was {stats.norm.ppf(0.95):.3f})")
print(f"95% CI: {low:.2f} to {high:.2f}")
check = stats.ttest_1samp(minutes, 0).confidence_interval()
assert np.isclose(low, check.low) and np.isclose(high, check.high)
Output
critical value 2.201 (was 1.645)
95% CI: 10.52 to 17.56

How it works:

  1. ppf(0.95) puts all 5% in one tail: it is the critical value of a one-sided interval. A two-sided 95% interval needs ppf(0.975).
  2. With n=12n = 12, the standard deviation is estimated, so the t distribution with 11 degrees of freedom applies. Its critical value, 2.201, is much larger than the buggy 1.645.
  3. The assert compares the result with SciPy’s own t-interval.

Alternative: stats.t.interval(0.95, df=n - 1, loc=minutes.mean(), scale=se) returns both ends in one call and leaves no room for the quantile mistake.

M29-W08 · Interpret a result: what does p = 0.04 say?

Section titled “M29-W08 · Interpret a result: what does p = 0.04 say?”
Warm-up

Interpret a result: a test of a discount email against no email gives a conversion difference with p = 0.04 (two-sided, α = 0.05). Mark each statement as true or false, then store your answers in a dict and print the letters of the true statements.

  • A. There is a 4% probability that the email has no effect.
  • B. If the email had no effect, a difference at least this large would occur in about 4% of experiments like this one.
  • C. The email increases conversion by a large amount.
  • D. At α = 0.05, we reject the null hypothesis of no difference.
  • E. If we repeated the experiment, we would get a p-value below 0.05 with 96% probability.
  • F. The probability of a Type I error for this decision rule is 5%.

Acceptance criteria:

  • Decide each statement before you open the solution, and write one reason for each.
  • Your list of true statements matches the Output of the solution.
Starter
answers = {
"A": None, # TODO: True or False
"B": None,
"C": None,
"D": None,
"E": None,
"F": None,
}
# TODO: print the sorted letters whose answer is True
Hint 1

The p-value is computed assuming H0 is true. Can it be the probability that H0 is true?

Hint 2

A p-value says nothing about the size of an effect or about the result of a repeat experiment. α is the Type I error rate of the decision rule.

Solution
answers = {
"A": False, # p assumes H0; it is not P(H0)
"B": True, # the definition of the p-value
"C": False, # p says nothing about size; look at the effect and its CI
"D": True, # 0.04 <= 0.05
"E": False, # replication probability is not 1 - p (and is often near 50%)
"F": True, # alpha is the Type I error rate of "reject when p <= 0.05"
}
true_letters = sorted(k for k, v in answers.items() if v)
print("True statements:", ", ".join(true_letters))
assert true_letters == ["B", "D", "F"]
Output
True statements: B, D, F

How it works:

  1. A and E are the classic misreadings: both treat 1−p1 - p as a probability about the hypotheses or the future.
  2. C confuses significance with importance. A tiny effect can have a small p-value in a large sample.
  3. F is about the rule, not this result: if you always reject at p≤0.05p \le 0.05, you make a Type I error in 5% of the experiments where H0 is true.

Alternative: test your understanding with a simulation. Run 1,000 A/A tests (no effect) as in the lesson. About 5% have p≤0.05p \le 0.05 (statement F). None of them has an effect, whatever its p-value (statement A).

Warm-up

Draw a random sample of 100 customers with random_state=42. Print the mean of logins_last_30d, its standard error, and the sample size needed to bring the standard error down to 0.5 logins (assume the standard deviation stays the same).

Expected output
mean 12.07 | sd 6.76 | SE 0.676
n for SE = 0.5: 183
Starter
sample = customers.sample(n=100, random_state=42)
logins = sample["logins_last_30d"]
# TODO: the standard error s / sqrt(n)
# TODO: solve s / sqrt(n) = 0.5 for n, and round up
Hint 1

stats.sem(logins) returns s/ns/\sqrt{n} with ddof=1.

Hint 2

From SE=s/n\text{SE} = s/\sqrt{n}, you get n=(s/SE)2n = (s / \text{SE})^2. Round up with np.ceil.

Solution
sample = customers.sample(n=100, random_state=42)
logins = sample["logins_last_30d"]
s = logins.std(ddof=1)
se = s / np.sqrt(len(logins))
n_needed = int(np.ceil((s / 0.5) ** 2))
print(f"mean {logins.mean():.2f} | sd {s:.2f} | SE {se:.3f}")
print(f"n for SE = 0.5: {n_needed}")
assert np.isclose(se, stats.sem(logins))
assert s / np.sqrt(n_needed) <= 0.5
Output
mean 12.07 | sd 6.76 | SE 0.676
n for SE = 0.5: 183

How it works:

  1. The standard error is the standard deviation divided by n\sqrt{n}. stats.sem computes the same value.
  2. To cut the standard error from 0.68 to 0.5, you need (0.676/0.5)2≈1.83(0.676/0.5)^2 \approx 1.83 times as many customers: 183 instead of 100. Halving it would need four times as many, because of the square root.
  3. The assert confirms that the rounded-up sample size meets the target.

Alternative: solve for the margin of error instead. For a 95% interval of ±1 login, you need n≈(1.96 s/1)2n \approx (1.96\,s / 1)^2.

Core

For the control group of ab, compute a 95% t-interval for the mean time_on_page_s by hand (xˉ±t0.975, n−1 s/n\bar{x} \pm t_{0.975,\,n-1}\, s/\sqrt{n}). Check it against stats.t.interval. Print the mean, the margin of error and the interval.

Expected output
n = 5002, mean 82.72 s, margin of error 1.46 s
95% CI by hand: 81.27 to 84.18 s
stats.t.interval: 81.27 to 84.18 s
Starter
time_c = ab.loc[ab["group"] == "control", "time_on_page_s"]
# TODO: n, mean, standard error with ddof=1
# TODO: t critical value with df = n - 1
# TODO: the interval by hand, and with stats.t.interval
Hint 1

se = time_c.std(ddof=1) / np.sqrt(n) and crit = stats.t.ppf(0.975, df=n - 1).

Hint 2

stats.t.interval(0.95, df=n - 1, loc=mean, scale=se) returns (low, high).

Solution
time_c = ab.loc[ab["group"] == "control", "time_on_page_s"]
n = len(time_c)
mean = time_c.mean()
se = time_c.std(ddof=1) / np.sqrt(n)
crit = stats.t.ppf(0.975, df=n - 1)
low, high = mean - crit * se, mean + crit * se
lib_low, lib_high = stats.t.interval(0.95, df=n - 1, loc=mean, scale=se)
print(f"n = {n}, mean {mean:.2f} s, margin of error {crit * se:.2f} s")
print(f"95% CI by hand: {low:.2f} to {high:.2f} s")
print(f"stats.t.interval: {lib_low:.2f} to {lib_high:.2f} s")
assert np.isclose(low, lib_low) and np.isclose(high, lib_high)
Output
n = 5002, mean 82.72 s, margin of error 1.46 s
95% CI by hand: 81.27 to 84.18 s
stats.t.interval: 81.27 to 84.18 s

How it works:

  1. With 5,002 users, the t critical value is 1.960, the same as the normal one.
  2. The standard error is small (about 0.74 s), so the interval is narrow: about ±1.5 s around the mean.
  3. Time on page is right-skewed, but with thousands of values the CLT makes the t-interval reliable.

Alternative: stats.ttest_1samp(time_c, 0).confidence_interval() returns the same interval. For a skewed variable and a small sample, a bootstrap interval is safer.

M29-C02 · Wald and Wilson intervals for rare churn

Section titled “M29-C02 · Wald and Wilson intervals for rare churn”
Core

Two-year customers rarely churn. (1) Among two-year customers who signed up in 2024, count the churners. Compute the 95% Wald interval by hand (p^±1.96p^(1−p^)/n\hat{p} \pm 1.96\sqrt{\hat{p}(1-\hat{p})/n}), then with proportion_confint(..., method="normal"), then the Wilson interval. (2) A pilot of 40 customers had 1 churner. Compute the three intervals for the pilot too. Which method gives an impossible answer, and how does statsmodels hide it?

Expected output
2024 two-year: 4/107 = 0.0374
Wald by hand +0.0014 to 0.0733
statsmodels +0.0014 to 0.0733
Wilson +0.0146 to 0.0922
pilot: 1/40 = 0.0250
Wald by hand -0.0234 to 0.0734
statsmodels +0.0000 to 0.0734
Wilson +0.0044 to 0.1288
Starter
from statsmodels.stats.proportion import proportion_confint
recent = customers[(customers["contract"] == "two-year") & (customers["signup_date"] >= "2024")]
# TODO: k and n for the recent two-year customers
# TODO: for (k, n) and for the pilot (1, 40): Wald by hand, "normal" and "wilson"
Hint 1

Dates in ISO format compare correctly as text: "2024-03-15" >= "2024" is True.

Hint 2

proportion_confint(k, n, alpha=0.05, method="normal") is the Wald interval, cut at 0 and 1; method="wilson" gives Wilson.

Solution
from statsmodels.stats.proportion import proportion_confint
two_year = customers["contract"] == "two-year"
recent = customers[two_year & (customers["signup_date"] >= "2024")]
k, n = int(recent["churned"].sum()), len(recent)
results = {}
for label, (kk, nn) in {"2024 two-year": (k, n), "pilot": (1, 40)}.items():
p_hat = kk / nn
margin = 1.96 * np.sqrt(p_hat * (1 - p_hat) / nn)
clipped = proportion_confint(kk, nn, alpha=0.05, method="normal")
wilson = proportion_confint(kk, nn, alpha=0.05, method="wilson")
results[label] = (p_hat - margin, clipped[0], wilson[0])
print(f"{label}: {kk}/{nn} = {p_hat:.4f}")
print(f" Wald by hand {p_hat - margin:+.4f} to {p_hat + margin:.4f}")
print(f" statsmodels {clipped[0]:+.4f} to {clipped[1]:.4f}")
print(f" Wilson {wilson[0]:+.4f} to {wilson[1]:.4f}")
wald_low, clipped_low, wilson_low = results["pilot"]
assert wald_low < 0 == clipped_low < wilson_low
Output
2024 two-year: 4/107 = 0.0374
Wald by hand +0.0014 to 0.0733
statsmodels +0.0014 to 0.0733
Wilson +0.0146 to 0.0922
pilot: 1/40 = 0.0250
Wald by hand -0.0234 to 0.0734
statsmodels +0.0000 to 0.0734
Wilson +0.0044 to 0.1288

How it works:

  1. The Wald interval is symmetric around p^\hat{p}. For the pilot, it reaches below 0: a negative churn rate is impossible.
  2. statsmodels cuts the Wald interval at 0. That hides the symptom but not the problem: a lower bound of exactly 0 is also impossible, because the pilot saw a churner. The interval is still too narrow on the right.
  3. The Wilson interval stays inside 0 to 1 and is skewed to the right, which matches the real uncertainty about a small proportion. The + in :+.4f shows the sign, so the negative bound stands out.

Alternative: for very small counts, the exact Clopper–Pearson interval (method="beta") guarantees at least 95% coverage. It is wider than Wilson.

M29-C03 · Bootstrap the median order value

Section titled “M29-C03 · Bootstrap the median order value”
Core

Among treatment buyers in ab (converted == 1), compute the median revenue and a 95% bootstrap confidence interval for it with stats.bootstrap. Use 5,000 resamples, rng=np.random.default_rng(42) and the percentile method. Then repeat with the default BCa method and a new generator with the same seed.

Expected output
n = 583, median 33.97 USD
percentile 95% CI 31.35 to 37.55 | SE 1.58
BCa 95% CI 31.35 to 37.58 | SE 1.58
Starter
buyers_t = ab.loc[(ab["group"] == "treatment") & (ab["converted"] == 1), "revenue"]
# TODO: the sample median
# TODO: stats.bootstrap((data,), np.median, n_resamples=5_000, method="percentile", rng=...)
# TODO: the same with the default method (BCa)
Hint 1

stats.bootstrap expects a tuple of samples: (buyers_t.to_numpy(),), with the trailing comma.

Hint 2

The result has .confidence_interval.low, .confidence_interval.high and .standard_error.

Solution
buyers_t = ab.loc[(ab["group"] == "treatment") & (ab["converted"] == 1), "revenue"]
data = (buyers_t.to_numpy(),)
print(f"n = {len(buyers_t)}, median {buyers_t.median():.2f} USD")
cis = {}
for method in ("percentile", "BCa"):
res = stats.bootstrap(
data, np.median, n_resamples=5_000, method=method,
rng=np.random.default_rng(42),
)
ci = res.confidence_interval
cis[method] = ci
print(
f"{method:<10} 95% CI {ci.low:.2f} to {ci.high:.2f}"
f" | SE {res.standard_error:.2f}"
)
assert all(ci.low < buyers_t.median() < ci.high for ci in cis.values())
Output
n = 583, median 33.97 USD
percentile 95% CI 31.35 to 37.55 | SE 1.58
BCa 95% CI 31.35 to 37.58 | SE 1.58

How it works:

  1. The median of a skewed variable has no simple standard-error formula, so the bootstrap resamples the 583 buyers 5,000 times and looks at the spread of the medians.
  2. The percentile method takes the 2.5th and 97.5th percentiles of the bootstrap medians. BCa shifts them to correct for bias and skew.
  3. A new generator with the same seed makes each run repeatable.

Alternative: a hand-written percentile bootstrap shows the idea in four lines: idx = rng.integers(0, n, size=(5_000, n)), meds = np.median(x[idx], axis=1), then np.percentile(meds, [2.5, 97.5]).

M29-C04 · One-sample t-test: the pricing claim

Section titled “M29-C04 · One-sample t-test: the pricing claim”
Core

The pricing team claims that the mean monthly charge is 60 USD. Draw 40 random customers (random_state=42) and test the claim with a two-sided one-sample t-test at α = 0.05. Print the sample mean, t, df, p, the 95% CI and the decision. Then interpret the result in one sentence.

Expected output
mean 62.96 | t = 0.792 | df = 39 | p = 0.433
95% CI 55.40 to 70.53 -> fail to reject H0
Starter
sample = customers.sample(n=40, random_state=42)["monthly_charges"]
# TODO: stats.ttest_1samp(sample, popmean=60)
# TODO: print mean, t, df, p and the CI; print "reject H0" or "fail to reject H0"
Hint 1

The result has .statistic, .pvalue, .df and a .confidence_interval() method.

Hint 2

decision = "reject H0" if res.pvalue <= 0.05 else "fail to reject H0".

Solution
sample = customers.sample(n=40, random_state=42)["monthly_charges"]
res = stats.ttest_1samp(sample, popmean=60)
ci = res.confidence_interval()
decision = "reject H0" if res.pvalue <= 0.05 else "fail to reject H0"
print(
f"mean {sample.mean():.2f} | t = {res.statistic:.3f}"
f" | df = {res.df} | p = {res.pvalue:.3f}"
)
print(f"95% CI {ci.low:.2f} to {ci.high:.2f} -> {decision}")
assert (ci.low <= 60 <= ci.high) == (res.pvalue > 0.05)
Output
mean 62.96 | t = 0.792 | df = 39 | p = 0.433
95% CI 55.40 to 70.53 -> fail to reject H0

How it works:

  1. The test statistic is the distance between the sample mean and 60, in standard errors.
  2. The p-value is large, so the sample is consistent with the claim. The 95% CI contains 60, which always agrees with “fail to reject” at α = 0.05; the assert checks this duality.
  3. Interpretation: “The survey gives no evidence against a mean of 60 USD, but with 40 customers it cannot pin the mean down more precisely than the interval shown.” Failing to reject is not proof that the mean is exactly 60.

Alternative: with skewed data and a small sample, the Wilcoxon signed-rank test on sample - 60 tests the center without assuming normal means: stats.wilcoxon(sample - 60).

M29-C05 · Interpret a non-significant Welch test

Section titled “M29-C05 · Interpret a non-significant Welch test”
Core

Do customers with autopay have longer sessions? Compare avg_session_minutes for has_autopay == 1 and has_autopay == 0 with a Welch t-test. Print both means, the p-value, the 95% CI of the difference and Cohen’s d. Interpret the result: is there “no difference”?

Expected output
autopay 14.39 min vs manual 14.28 min
p = 0.633, 95% CI of the difference -0.33 to 0.54 min
Cohen's d = 0.014
Starter
auto = customers.loc[customers["has_autopay"] == 1, "avg_session_minutes"]
manual = customers.loc[customers["has_autopay"] == 0, "avg_session_minutes"]
# TODO: Welch t-test with equal_var=False and its confidence_interval()
# TODO: Cohen's d with the pooled standard deviation
Hint 1

stats.ttest_ind(auto, manual, equal_var=False) returns a result with .confidence_interval().

Hint 2

Pooled sd: np.sqrt(((n1 - 1) * auto.var() + (n2 - 1) * manual.var()) / (n1 + n2 - 2)).

Solution
auto = customers.loc[customers["has_autopay"] == 1, "avg_session_minutes"]
manual = customers.loc[customers["has_autopay"] == 0, "avg_session_minutes"]
res = stats.ttest_ind(auto, manual, equal_var=False)
ci = res.confidence_interval()
n1, n2 = len(auto), len(manual)
pooled = np.sqrt(((n1 - 1) * auto.var() + (n2 - 1) * manual.var()) / (n1 + n2 - 2))
d = (auto.mean() - manual.mean()) / pooled
print(f"autopay {auto.mean():.2f} min vs manual {manual.mean():.2f} min")
print(
f"p = {res.pvalue:.3f}, 95% CI of the difference "
f"{ci.low:.2f} to {ci.high:.2f} min"
)
print(f"Cohen's d = {d:.3f}")
assert ci.low < 0 < ci.high
assert abs(d) < 0.05
Output
autopay 14.39 min vs manual 14.28 min
p = 0.633, 95% CI of the difference -0.33 to 0.54 min
Cohen's d = 0.014

How it works:

  1. The p-value is large, so you fail to reject H0.
  2. The CI is the more useful number: the true difference is between about −0.3 and +0.5 minutes. With 5,000 customers, the test had plenty of power, so this is evidence that any difference is tiny, not just a lack of evidence.
  3. Interpretation: “Autopay and manual payers have practically the same session length (difference under half a minute either way).” Say “no meaningful difference”, backed by the narrow CI, rather than “no difference”.

Alternative: an equivalence test (TOST, two one-sided tests) formally tests “the difference is within ±1 minute”. statsmodels provides it as statsmodels.stats.weightstats.ttost_ind.

Core

Fix the bug: an analyst compares monthly revenue in 2023 and 2024 (12 months each) and concludes that growth is not significant. The months are paired: January 2023 belongs with January 2024. Fix the test and print the mean monthly growth, the wrong and the right p-value.

Expected output
mean monthly growth 25,445 USD; months that grew: 10/12
unpaired p = 0.255 (wrong)
paired p = 0.0059
monthly revenue range: 77,405 to 302,912 USD
months that shrank: ['05', '08']
Starter
sales["year"] = sales["order_date"].str[:4]
sales["month"] = sales["order_date"].str[5:7]
monthly = sales.pivot_table(
index="month", columns="year", values="revenue", aggfunc="sum"
)
res = stats.ttest_ind(monthly["2024"], monthly["2023"]) # TODO: the bug is here
print(f"p = {res.pvalue:.3f}")
Hint 1

Strong seasonality makes December very different from February in both years. Which test removes the month-to-month differences?

Hint 2

stats.ttest_rel(after, before) tests the paired differences.

Solution
sales["year"] = sales["order_date"].str[:4]
sales["month"] = sales["order_date"].str[5:7]
monthly = sales.pivot_table(
index="month", columns="year", values="revenue", aggfunc="sum"
)
wrong = stats.ttest_ind(monthly["2024"], monthly["2023"])
right = stats.ttest_rel(monthly["2024"], monthly["2023"])
growth = monthly["2024"] - monthly["2023"]
print(
f"mean monthly growth {growth.mean():,.0f} USD; "
f"months that grew: {(growth > 0).sum()}/12"
)
print(f"unpaired p = {wrong.pvalue:.3f} (wrong)")
print(f"paired p = {right.pvalue:.4f}")
low, high = monthly.min().min(), monthly.max().max()
print(f"monthly revenue range: {low:,.0f} to {high:,.0f} USD")
print("months that shrank:", growth[growth < 0].index.tolist())
assert right.pvalue < 0.01 < wrong.pvalue
assert np.isclose(right.pvalue, stats.ttest_1samp(growth, 0).pvalue)
Output
mean monthly growth 25,445 USD; months that grew: 10/12
unpaired p = 0.255 (wrong)
paired p = 0.0059
monthly revenue range: 77,405 to 302,912 USD
months that shrank: ['05', '08']

How it works:

  1. The unpaired test compares two groups of 12 numbers. The seasonal spread (77,000 to 303,000 USD per month) is huge compared with the growth, so the groups overlap.
  2. The paired test works on the 12 differences. Seasonality cancels out, and a consistent growth of about 25,000 USD per month remains.
  3. Two months shrank (May and August), but the evidence for overall growth is strong.

Alternative: test the relative growth instead: stats.ttest_1samp(np.log(monthly["2024"] / monthly["2023"]), 0). It asks whether the typical month grew by a constant percentage, which suits multiplicative business growth.

M29-C07 · Chi-square: payment method and churn

Section titled “M29-C07 · Chi-square: payment method and churn”
Core

Test whether churn is related to payment_method. Print the churn rate per method, χ², df, the p-value, the smallest expected count and Cramér’s V. Is the association statistically significant? Is it strong?

Expected output
{'credit_card': 0.158, 'bank_transfer': 0.174, 'paypal': 0.174, 'electronic_check': 0.248}
chi2 = 45.5, df = 3, p = 7.1e-10
smallest expected count 167.2, Cramer's V = 0.095
Starter
ct = pd.crosstab(customers["payment_method"], customers["churned"])
# TODO: churn rate per method with groupby
# TODO: stats.chi2_contingency(ct)
# TODO: stats.contingency.association(ct, method="cramer")
Hint 1

The result of chi2_contingency has .statistic, .pvalue, .dof and .expected_freq.

Hint 2

res.expected_freq.min() checks the “at least 5 per cell” rule.

Solution
ct = pd.crosstab(customers["payment_method"], customers["churned"])
rates = customers.groupby("payment_method")["churned"].mean().sort_values()
print(rates.round(3).to_dict())
res = stats.chi2_contingency(ct)
v = stats.contingency.association(ct, method="cramer")
print(f"chi2 = {res.statistic:.1f}, df = {res.dof}, p = {res.pvalue:.1e}")
print(f"smallest expected count {res.expected_freq.min():.1f}, Cramer's V = {v:.3f}")
assert res.dof == 3 and res.pvalue < 0.001 and v < 0.2
Output
{'credit_card': 0.158, 'bank_transfer': 0.174, 'paypal': 0.174, 'electronic_check': 0.248}
chi2 = 45.5, df = 3, p = 7.1e-10
smallest expected count 167.2, Cramer's V = 0.095

How it works:

  1. With 4 methods and 2 outcomes, df = (4 − 1)(2 − 1) = 3.
  2. The p-value is tiny: churn clearly depends on the payment method. Electronic-check payers churn most.
  3. Cramér’s V of about 0.1 is a weak association, much weaker than contract type (0.30 in the lesson). Significant does not mean strong.

Alternative: compare electronic check with all other methods in a 2×2 table and report an odds ratio with stats.contingency.odds_ratio. An odds ratio with a CI is easier to explain to a business audience than V.

M29-C08 · Choose a method: order value by device

Section titled “M29-C08 · Choose a method: order value by device”
Core

Choose a method and justify it: compare the revenue of buyers (converted == 1) across the three devices. Revenue per buyer is log-normal and has outliers. Print the median per device, then run the test you choose. Also run one-way ANOVA on the log of revenue as a second view. Write your conclusion.

Expected output
median count
device
desktop 32.25 454
mobile 35.84 516
tablet 37.99 119
Kruskal-Wallis H = 5.90, p = 0.052
ANOVA on log revenue F = 3.35, p = 0.036
Starter
buyers = ab[ab["converted"] == 1]
# TODO: median and count of revenue per device
# TODO: the list of revenue arrays, one per device
# TODO: your chosen test, then ANOVA on np.log of each array
Hint 1

Three independent groups, skewed values, unequal sizes (the tablet group is small): which test from the “Choosing a test” table fits?

Hint 2

groups = [g.to_numpy() for _, g in buyers.groupby("device")["revenue"]], then stats.kruskal(*groups).

Solution
buyers = ab[ab["converted"] == 1]
print(buyers.groupby("device")["revenue"].agg(["median", "count"]).round(2))
groups = [g.to_numpy() for _, g in buyers.groupby("device")["revenue"]]
kw = stats.kruskal(*groups)
anova_log = stats.f_oneway(*[np.log(g) for g in groups])
print(f"Kruskal-Wallis H = {kw.statistic:.2f}, p = {kw.pvalue:.3f}")
print(f"ANOVA on log revenue F = {anova_log.statistic:.2f}, p = {anova_log.pvalue:.3f}")
assert 0.05 < kw.pvalue < 0.06 and anova_log.pvalue < 0.05
Output
median count
device
desktop 32.25 454
mobile 35.84 516
tablet 37.99 119
Kruskal-Wallis H = 5.90, p = 0.052
ANOVA on log revenue F = 3.35, p = 0.036

How it works:

  1. Choice: Kruskal–Wallis, because the groups are strongly skewed with outliers, and ANOVA on raw revenue would let a few large orders dominate the result.
  2. Kruskal–Wallis gives p ≈ 0.052; ANOVA on the log scale gives p ≈ 0.036. The two views disagree around the 0.05 line.
  3. Conclusion: there is weak evidence that desktop buyers spend a little less per order (median about 32 USD against 36–38 USD). It is not strong enough to act on alone. A borderline result calls for a replication, not for choosing the test whose p-value you like.

Alternative: a bootstrap CI for the difference in medians, desktop versus mobile, puts a size on the effect. It answers “how much less?”, which neither test does.

Core

Compare logins_last_30d for churners and stayers with a two-sided Mann–Whitney U test. Print the medians, U, the p-value and the probability that a random churner logs in more often than a random stayer (U/(n1n2)U / (n_1 n_2), with churners as the first sample).

Expected output
median logins: churners 9, stayers 10
U = 1,632,782.5, p = 1.0e-14
P(churner logs in more than a stayer) = 0.420
Starter
churn_logins = customers.loc[customers["churned"] == 1, "logins_last_30d"]
stay_logins = customers.loc[customers["churned"] == 0, "logins_last_30d"]
# TODO: medians
# TODO: stats.mannwhitneyu(churn_logins, stay_logins, alternative="two-sided")
# TODO: U / (n1 * n2)
Hint 1

mannwhitneyu returns U for the first sample. The order of the arguments decides the direction of the probability.

Hint 2

A value below 0.5 means churners tend to have fewer logins.

Solution
churn_logins = customers.loc[customers["churned"] == 1, "logins_last_30d"]
stay_logins = customers.loc[customers["churned"] == 0, "logins_last_30d"]
mw = stats.mannwhitneyu(churn_logins, stay_logins, alternative="two-sided")
prob = mw.statistic / (len(churn_logins) * len(stay_logins))
medians = (churn_logins.median(), stay_logins.median())
print(f"median logins: churners {medians[0]:.0f}, stayers {medians[1]:.0f}")
print(f"U = {mw.statistic:,.1f}, p = {mw.pvalue:.1e}")
print(f"P(churner logs in more than a stayer) = {prob:.3f}")
assert prob < 0.5 and mw.pvalue < 0.001
Output
median logins: churners 9, stayers 10
U = 1,632,782.5, p = 1.0e-14
P(churner logs in more than a stayer) = 0.420

How it works:

  1. Logins are counts with a long right tail, so a rank test is a good fit.
  2. The p-value is tiny: the two distributions differ.
  3. The probability of 0.42 says that in 42% of churner–stayer pairs, the churner logs in more (ties count half). The effect is real but modest. The rank-biserial correlation, 1−2U/(n1n2)1 - 2U/(n_1 n_2), expresses the same thing on a −1 to 1 scale.

Alternative: stats.ttest_ind(churn_logins, stay_logins, equal_var=False) compares the means. With thousands of rows it is valid here too, and it answers a different question: the difference in average logins.

Core

Compute two effect sizes. (1) Cohen’s d for tenure_months, churners minus stayers. (2) The odds ratio of churn for customers without autopay compared with customers with autopay: first by hand from the four counts, then with stats.contingency.odds_ratio, with its 95% CI.

Expected output
Cohen's d, tenure: -0.742
odds ratio by hand: 1.373
scipy (conditional MLE): 1.373, 95% CI 1.189 to 1.585
Starter
def cohens_d(a, b):
# TODO: difference in means divided by the pooled standard deviation
...
# TODO: d for tenure_months
# TODO: a 2x2 table: rows no autopay / autopay, columns churned 1 / 0
# TODO: odds ratio by hand and with stats.contingency.odds_ratio
Hint 1

pd.crosstab(customers["has_autopay"], customers["churned"]).loc[[0, 1], [1, 0]] orders the table as [[exposed & event, exposed & no event], […]] with “no autopay” (0) as the exposed row.

Hint 2

By hand: OR=a/bc/d=adbc\text{OR} = \frac{a/b}{c/d} = \frac{ad}{bc} for the table [[a, b], [c, d]].

Solution
def cohens_d(a: pd.Series, b: pd.Series) -> float:
n1, n2 = len(a), len(b)
pooled = np.sqrt(((n1 - 1) * a.var() + (n2 - 1) * b.var()) / (n1 + n2 - 2))
return (a.mean() - b.mean()) / pooled
churned = customers["churned"] == 1
tenure = customers["tenure_months"]
d = cohens_d(tenure[churned], tenure[~churned])
table = pd.crosstab(customers["has_autopay"], customers["churned"]).loc[[0, 1], [1, 0]]
(a, b), (c, dd) = table.to_numpy()
or_hand = (a * dd) / (b * c)
res = stats.contingency.odds_ratio(table.to_numpy())
ci = res.confidence_interval()
print(f"Cohen's d, tenure: {d:.3f}")
print(f"odds ratio by hand: {or_hand:.3f}")
print(
f"scipy (conditional MLE): {res.statistic:.3f}, "
f"95% CI {ci.low:.3f} to {ci.high:.3f}"
)
assert d < -0.5
assert abs(or_hand - res.statistic) < 0.01 and ci.low > 1
Output
Cohen's d, tenure: -0.742
odds ratio by hand: 1.373
scipy (conditional MLE): 1.373, 95% CI 1.189 to 1.585

How it works:

  1. Churners have about 0.74 pooled standard deviations less tenure: a medium-to-large effect.
  2. The odds of churning are about 1.38 times higher without autopay. The CI excludes 1, so the association is significant.
  3. SciPy’s default estimate (the conditional maximum likelihood) agrees with the hand formula to three decimals at this sample size. kind="sample" returns the hand formula exactly.

Alternative: report the difference in churn rates too (21.9% against 16.9%, 5 percentage points). Many readers understand rates better than odds.

Core

A retention campaign aims to cut the churn rate from 19.3% to 16%. Use proportion_effectsize and NormalIndPower to print: Cohen’s h, the customers needed per group for 80% and for 90% power (two-sided, α = 0.05), and the power you would get with only 1,000 customers per group.

Expected output
Cohen's h = -0.0866 (by hand -0.0866)
power 80%: 2,092 customers per group
power 90%: 2,800 customers per group
power with 1,000 per group: 0.491
Starter
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize
# TODO: h = proportion_effectsize(0.16, 0.193)
# TODO: solve_power for power 0.80 and 0.90; round up
# TODO: power(effect_size=h, nobs1=1000, alpha=0.05)
Hint 1

Leave out the quantity you want: solve_power(effect_size=h, alpha=0.05, power=0.80) returns nobs1.

Hint 2

The sign of h does not matter for a two-sided test; the power functions use its absolute value.

Solution
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize
h = proportion_effectsize(0.16, 0.193)
analysis = NormalIndPower()
h_manual = 2 * np.arcsin(np.sqrt(0.16)) - 2 * np.arcsin(np.sqrt(0.193))
print(f"Cohen's h = {h:.4f} (by hand {h_manual:.4f})")
needed = {}
for power in (0.80, 0.90):
n_float = analysis.solve_power(effect_size=h, alpha=0.05, power=power)
needed[power] = int(np.ceil(n_float))
print(f"power {power:.0%}: {needed[power]:,} customers per group")
power_1000 = analysis.power(effect_size=h, nobs1=1000, alpha=0.05)
print(f"power with 1,000 per group: {power_1000:.3f}")
assert needed[0.90] > needed[0.80] and power_1000 < 0.80
Output
Cohen's h = -0.0866 (by hand -0.0866)
power 80%: 2,092 customers per group
power 90%: 2,800 customers per group
power with 1,000 per group: 0.491

How it works:

  1. Cohen’s h is the difference of the arcsine-transformed proportions, h=2arcsin⁡p1−2arcsin⁡p2h = 2\arcsin\sqrt{p_1} - 2\arcsin\sqrt{p_2}. It is negative here because the target rate is lower.
  2. Going from 80% to 90% power costs about a third more customers.
  3. With 1,000 per group, the campaign would detect a real 3.3-point drop only about half the time: a coin flip. Plan for the larger sample, or target a larger effect.

Alternative: simulate the experiment many times and count how often the z-test rejects (Challenge M29-X06 does this). Simulation also handles designs that have no formula, such as unequal groups with a ratio test.

M29-C12 · Refactor: a vectorized bootstrap

Section titled “M29-C12 · Refactor: a vectorized bootstrap”
Core

Refactor: the loop below bootstraps the mean revenue per user of the treatment group 2,000 times. Rewrite it without a Python loop: draw all resample indices in one rng.integers call with size=(2_000, n). Show that both versions give exactly the same 2,000 means and the same 95% percentile interval.

Expected output
identical results: True
mean revenue per user 4.846 USD, 95% CI 4.385 to 5.293
Starter
rev = ab.loc[ab["group"] == "treatment", "revenue"].to_numpy()
n = len(rev)
rng = np.random.default_rng(42)
loop_means = np.empty(2_000)
for i in range(2_000):
idx = rng.integers(0, n, size=n)
loop_means[i] = rev[idx].mean()
# TODO: a new generator with seed 42, one integers() call, one mean(axis=1)
# TODO: compare the arrays and print the percentile interval
Hint 1

rng.integers(0, n, size=(2_000, n)) returns a 2-D array of indices. rev[idx] turns it into a 2-D array of values.

Hint 2

The generator produces the same stream of numbers whether you ask for them in 2,000 small calls or one big call, as long as the type and bounds are the same.

Solution
rev = ab.loc[ab["group"] == "treatment", "revenue"].to_numpy()
n = len(rev)
rng = np.random.default_rng(42)
loop_means = np.empty(2_000)
for i in range(2_000):
idx = rng.integers(0, n, size=n)
loop_means[i] = rev[idx].mean()
rng = np.random.default_rng(42)
vec_means = rev[rng.integers(0, n, size=(2_000, n))].mean(axis=1)
low, high = np.percentile(vec_means, [2.5, 97.5])
print(f"identical results: {np.array_equal(loop_means, vec_means)}")
print(f"mean revenue per user {rev.mean():.3f} USD, 95% CI {low:.3f} to {high:.3f}")
assert np.array_equal(loop_means, vec_means)
assert low < rev.mean() < high
Output
identical results: True
mean revenue per user 4.846 USD, 95% CI 4.385 to 5.293

How it works:

  1. Row i of the index matrix plays the role of loop iteration i. NumPy fills the matrix row by row from the same random stream, so the draws are identical.
  2. rev[idx] uses fancy indexing (module 23) to build all 2,000 resamples at once, and .mean(axis=1) averages each row.
  3. The vectorized version is much faster. It needs memory for 2,000 × 4,998 indices and as many values (about 80 MB each); for bigger problems, process the resamples in chunks.

Alternative: stats.bootstrap((rev,), np.mean, n_resamples=2_000, method="percentile", rng=...) does the same and also offers BCa. Use the manual version when you need the raw bootstrap values, for example to plot them.

M29-C13 · Multiple testing across countries

Section titled “M29-C13 · Multiple testing across countries”
Core

The A/B test ran in seven countries. For each country, run a two-proportion z-test of treatment against control with proportions_ztest. Collect the raw p-values, then adjust them with Bonferroni and with Benjamini–Hochberg (multipletests). Print one row per country, sorted by the raw p-value, and the number of significant countries for each method.

Expected output
country lift_pp p p_bonf p_bh
0 CA 4.443 0.025 0.176 0.176
1 FR 3.537 0.068 0.474 0.237
2 DE 2.791 0.120 0.840 0.280
3 US 1.216 0.209 1.000 0.340
4 AU -2.575 0.243 1.000 0.340
5 UK 1.060 0.516 1.000 0.603
6 IN -1.136 0.707 1.000 0.707
significant raw: 1 | Bonferroni: 0 | BH: 0
Starter
from statsmodels.stats.multitest import multipletests
from statsmodels.stats.proportion import proportions_ztest
rows = []
for country, part in ab.groupby("country"):
# TODO: buyers and users per group; the z-test; append a dict
...
# TODO: a DataFrame; add p_bonf and p_bh columns; sort by p
Hint 1

Inside the loop: k = part.groupby("group")["converted"].sum() and n = part.groupby("group")["converted"].count().

Hint 2

multipletests(p, method="bonferroni")[1] returns the adjusted p-values; use method="fdr_bh" for BH.

Solution
from statsmodels.stats.multitest import multipletests
from statsmodels.stats.proportion import proportions_ztest
rows = []
for country, part in ab.groupby("country"):
k = part.groupby("group")["converted"].sum()
n = part.groupby("group")["converted"].count()
_, p = proportions_ztest(
[k["treatment"], k["control"]], [n["treatment"], n["control"]]
)
lift = k["treatment"] / n["treatment"] - k["control"] / n["control"]
rows.append({"country": country, "lift_pp": 100 * lift, "p": p})
res = pd.DataFrame(rows)
res["p_bonf"] = multipletests(res["p"], method="bonferroni")[1]
res["p_bh"] = multipletests(res["p"], method="fdr_bh")[1]
res = res.sort_values("p").reset_index(drop=True)
print(res.round(3))
print("significant raw:", (res["p"] <= 0.05).sum(),
"| Bonferroni:", (res["p_bonf"] <= 0.05).sum(),
"| BH:", (res["p_bh"] <= 0.05).sum())
assert (res["p_bonf"] >= res["p"]).all() and (res["p_bh"] >= res["p"]).all()
Output
country lift_pp p p_bonf p_bh
0 CA 4.443 0.025 0.176 0.176
1 FR 3.537 0.068 0.474 0.237
2 DE 2.791 0.120 0.840 0.280
3 US 1.216 0.209 1.000 0.340
4 AU -2.575 0.243 1.000 0.340
5 UK 1.060 0.516 1.000 0.603
6 IN -1.136 0.707 1.000 0.707
significant raw: 1 | Bonferroni: 0 | BH: 0

How it works:

  1. Each country gets its own test, so seven tests run at once.
  2. The raw p-values flag only Canada. After either correction, no single country is significant: each country has too few users for its own verdict.
  3. The overall test pools all countries and is significant. Countries with negative lifts (Australia, India) are small and noisy; they are not evidence that the page hurts there.

Alternative: a single model with an interaction term, such as a logistic regression of converted ~ group * country, tests “does the lift differ between countries?” with one test instead of seven.

Core

Interpret a result: fit np.log(price) ~ np.log(sqft) + has_pool + C(neighborhood) on houses with smf.ols. Print the elasticity of price with respect to size with its 95% CI, the pool effect as a percent with its 95% CI, and R2R^2. Do not print summary(). Then write one sentence for each coefficient.

Expected output
elasticity 0.756 (95% CI 0.731 to 0.780)
pool effect +10.2% (95% CI +7.3% to +13.2%)
R-squared 0.819, n = 3000
Starter
model = smf.ols("np.log(price) ~ np.log(sqft) + has_pool + C(neighborhood)", data=houses).fit()
ci = model.conf_int()
# TODO: the coefficient and CI of np.log(sqft)
# TODO: the pool effect: 100 * (exp(coef) - 1), and the same for both CI ends
# TODO: model.rsquared
Hint 1

model.params["np.log(sqft)"] and ci.loc["np.log(sqft)"] give the coefficient and its interval.

Hint 2

Transform the interval ends the same way as the coefficient: 100 * (np.exp(ci.loc["has_pool"]) - 1).

Solution
formula = "np.log(price) ~ np.log(sqft) + has_pool + C(neighborhood)"
model = smf.ols(formula, data=houses).fit()
ci = model.conf_int()
el = model.params["np.log(sqft)"]
el_lo, el_hi = ci.loc["np.log(sqft)"]
pool = 100 * (np.exp(model.params["has_pool"]) - 1)
pool_lo, pool_hi = 100 * (np.exp(ci.loc["has_pool"]) - 1)
print(f"elasticity {el:.3f} (95% CI {el_lo:.3f} to {el_hi:.3f})")
print(f"pool effect {pool:+.1f}% (95% CI {pool_lo:+.1f}% to {pool_hi:+.1f}%)")
print(f"R-squared {model.rsquared:.3f}, n = {model.nobs:.0f}")
assert 0 < el < 1 and pool_lo > 0
Output
elasticity 0.756 (95% CI 0.731 to 0.780)
pool effect +10.2% (95% CI +7.3% to +13.2%)
R-squared 0.819, n = 3000

How it works:

  1. Size: “Within a neighborhood, and with the pool status fixed, a house 1% larger sells for about 0.75% more on average.” An elasticity below 1 means diminishing returns to size.
  2. Pool: “A pool goes with a price about 10% higher (CI 7% to 13%), holding size and neighborhood fixed.” The CI excludes 0. Without the condition variable, this coefficient may also absorb other differences between houses with and without pools.
  3. R2R^2 says the model explains about 82% of the variance of log price. Transform the CI ends of a log coefficient with the same eβ−1e^{\beta} - 1 as the estimate.

Alternative: model.get_prediction(new_rows).summary_frame(alpha=0.05) gives prediction intervals for new houses, which answer “how far off can one prediction be?” rather than “how sure are we about the average effect?”.

M29-X01 · A permutation test for revenue per user

Section titled “M29-X01 · A permutation test for revenue per user”
Challenge

Revenue per user in ab is mostly zeros with a long right tail. Test whether treatment changed the mean revenue per user with a permutation test: shuffle the group labels 5,000 times with rng = np.random.default_rng(42) and rng.permutation, and compute the two-sided p-value. Compare it with Welch’s t-test. Then compute the p-value with the “+1” correction, (count+1)/(B+1)(\text{count} + 1)/(B + 1), which never reports exactly 0.

Expected output
observed difference 0.466 USD per user
permutation p = 0.1534 | with +1 = 0.1536 | Welch p = 0.1567
Starter
rev = ab["revenue"].to_numpy()
is_t = (ab["group"] == "treatment").to_numpy()
# TODO: the observed difference in means
# TODO: 5,000 shuffles; store the shuffled differences
# TODO: two-sided p-value: share of |shuffled| >= |observed|
# TODO: Welch's t-test for comparison; the +1 corrected p-value
Hint 1

Inside the loop: perm = rng.permutation(is_t), then rev[perm].mean() - rev[~perm].mean().

Hint 2

Count the extreme shuffles with (np.abs(diffs) >= abs(observed)).sum().

Hint 3

The two p-values measure the same thing in different ways. With 10,000 users, they should be close.

Solution
rev = ab["revenue"].to_numpy()
is_t = (ab["group"] == "treatment").to_numpy()
observed = rev[is_t].mean() - rev[~is_t].mean()
rng = np.random.default_rng(42)
B = 5_000
diffs = np.empty(B)
for i in range(B):
perm = rng.permutation(is_t)
diffs[i] = rev[perm].mean() - rev[~perm].mean()
extreme = int((np.abs(diffs) >= abs(observed)).sum())
p_perm = extreme / B
p_plus1 = (extreme + 1) / (B + 1)
welch = stats.ttest_ind(rev[is_t], rev[~is_t], equal_var=False)
print(f"observed difference {observed:.3f} USD per user")
print(
f"permutation p = {p_perm:.4f} | with +1 = {p_plus1:.4f} | "
f"Welch p = {welch.pvalue:.4f}"
)
assert abs(p_perm - welch.pvalue) < 0.02
assert p_plus1 > p_perm
Output
observed difference 0.466 USD per user
permutation p = 0.1534 | with +1 = 0.1536 | Welch p = 0.1567

How it works:

  1. Under H0, the label of each user is arbitrary, so every shuffle is an equally likely version of the data. The shuffled differences form the null distribution.
  2. The p-value is the share of shuffles at least as extreme as the real difference. It agrees closely with Welch’s test (0.153 against 0.157): with 5,000 users per group, the CLT makes the t-test accurate even for this skewed metric.
  3. The +1 correction counts the observed data as one of the permutations. It keeps the p-value valid and avoids reporting “p = 0” when no shuffle is as extreme.

Alternative: stats.permutation_test((rev[is_t], rev[~is_t]), lambda x, y: x.mean() - y.mean(), n_resamples=5_000, rng=np.random.default_rng(42)) runs the same test, including the +1 correction.

Challenge

Simulate 2,000 A/A tests in which both groups convert at 10%. Each test adds 1,000 users per group per day for 10 days. An impatient analyst runs a two-proportion z-test after every day and stops at the first p≤0.05p \le 0.05. Print the false-positive rate when you test only once at the end, and when you peek every day. Then show that testing each look at α = 0.005 brings the peeking rate back below 5%.

Expected output
false positives, one test at the end: 0.051
false positives, peeking every day: 0.191
peeking with alpha 0.005 per look: 0.022
Starter
rng = np.random.default_rng(42)
sims, looks, batch = 2_000, 10, 1_000
# TODO: daily buyers per group: rng.binomial(batch, 0.10, size=(sims, looks)), then cumsum(axis=1)
# TODO: users per group at each look: batch * np.arange(1, looks + 1)
# TODO: pooled z and two-sided p for every simulation and every look
# TODO: false positives: final look only; any look; any look at 0.005
Hint 1

Draw group A first, then group B, each with shape (sims, looks). cumsum(axis=1) turns daily buyers into running totals.

Hint 2

NumPy broadcasting divides a (sims, looks) array by a (looks,) array column by column.

Hint 3

(p <= 0.05).any(axis=1) is True for each simulation that is significant at some look.

Solution
rng = np.random.default_rng(42)
sims, looks, batch = 2_000, 10, 1_000
buyers_a = rng.binomial(batch, 0.10, size=(sims, looks)).cumsum(axis=1)
buyers_b = rng.binomial(batch, 0.10, size=(sims, looks)).cumsum(axis=1)
n = batch * np.arange(1, looks + 1) # users per group after each day
p_a, p_b = buyers_a / n, buyers_b / n
pool = (buyers_a + buyers_b) / (2 * n)
z = (p_b - p_a) / np.sqrt(pool * (1 - pool) * 2 / n)
p = 2 * stats.norm.sf(np.abs(z))
final_only = (p[:, -1] <= 0.05).mean()
any_look = (p <= 0.05).any(axis=1).mean()
strict = (p <= 0.005).any(axis=1).mean()
print(f"false positives, one test at the end: {final_only:.3f}")
print(f"false positives, peeking every day: {any_look:.3f}")
print(f"peeking with alpha 0.005 per look: {strict:.3f}")
assert any_look > 2 * final_only and strict < 0.05
Output
false positives, one test at the end: 0.051
false positives, peeking every day: 0.191
peeking with alpha 0.005 per look: 0.022

How it works:

  1. Running totals make the ten looks of one test strongly correlated, as in a real experiment.
  2. A single test at the end has the promised 5% false-positive rate. Peeking ten times and stopping at the first “win” raises it to about 19%: almost one A/A test in five “finds” an effect.
  3. A stricter threshold per look restores control. Real sequential testing methods (such as alpha-spending functions) choose the per-look thresholds more cleverly, so they keep more power than this simple fix.

Alternative: also record when each false positive happened, with (p <= 0.05).argmax(axis=1) on the simulations that stop. With this seed, about half of the early stops happen on day 1 or day 2: each new look adds fewer new false positives, because the running totals change less from day to day.

M29-X03 · Coverage of Wald, Wilson and exact intervals

Section titled “M29-X03 · Coverage of Wald, Wilson and exact intervals”
Challenge

For a rare event (true rate 5%) and a small sample (n = 40), simulate 20,000 samples with rng.binomial(40, 0.05, size=20_000) and rng = np.random.default_rng(42). For each of the methods "normal" (Wald), "wilson" and "beta" (Clopper–Pearson), compute the 95% intervals with proportion_confint (it accepts arrays) and print the coverage and the average width.

Expected output
samples with 0 events: 0.127
normal coverage 0.869 | mean width 0.108
wilson coverage 0.952 | mean width 0.146
beta coverage 0.985 | mean width 0.157
Starter
from statsmodels.stats.proportion import proportion_confint
rng = np.random.default_rng(42)
k = rng.binomial(40, 0.05, size=20_000)
# TODO: for each method: lo, hi = proportion_confint(k, 40, alpha=0.05, method=method)
# TODO: coverage = share of intervals with lo <= 0.05 <= hi; average width = mean(hi - lo)
Hint 1

proportion_confint works element by element on a NumPy array of counts.

Hint 2

When a sample has 0 events, the Wald interval is (0, 0). Can it contain the true rate?

Solution
from statsmodels.stats.proportion import proportion_confint
rng = np.random.default_rng(42)
true_p, n = 0.05, 40
k = rng.binomial(n, true_p, size=20_000)
coverage = {}
print(f"samples with 0 events: {(k == 0).mean():.3f}")
for method in ("normal", "wilson", "beta"):
lo, hi = proportion_confint(k, n, alpha=0.05, method=method)
coverage[method] = ((lo <= true_p) & (true_p <= hi)).mean()
width = np.mean(hi - lo)
print(f"{method:<7} coverage {coverage[method]:.3f} | mean width {width:.3f}")
assert coverage["normal"] < 0.90 < 0.95 <= coverage["beta"]
Output
samples with 0 events: 0.127
normal coverage 0.869 | mean width 0.108
wilson coverage 0.952 | mean width 0.146
beta coverage 0.985 | mean width 0.157

How it works:

  1. About 13% of samples contain no event at all. The Wald interval is then (0, 0) and must miss the true rate. Its coverage falls far below the promised 95%.
  2. Wilson comes close to 95% with a moderate width.
  3. Clopper–Pearson (“exact”) guarantees at least 95% coverage and pays for it with the widest intervals. For a rare event and a small sample, prefer Wilson, or Clopper–Pearson when under-coverage is unacceptable (for example in a safety report).

Alternative: repeat the simulation for true_p from 0.01 to 0.5 and plot the coverage of each method against true_p. The Wald coverage curve oscillates and drops sharply near 0, while Wilson stays close to 0.95.

Challenge

Simulate 2,000 customers with rng = np.random.default_rng(42). Tenure is uniform from 0 to 60 months. Long-tenure customers use coupons more often (p_coupon = 1 / (1 + np.exp(-(tenure - 30) / 8))). Monthly spend is 40 + 1.5 * tenure + 5 * coupon + noise with noise sd 15, so a coupon truly adds 5 USD. (1) Fit spend ~ coupon and spend ~ coupon + tenure and print the coupon effect with its 95% CI. (2) Then assign coupons at random (probability 0.5) with the same generator and refit spend ~ coupon. Which models recover the true effect?

Expected output
observational, naive 41.36 USD (95% CI 39.24 to 43.49)
observational, adjusted 4.21 USD (95% CI 2.36 to 6.06)
randomized, naive 6.44 USD (95% CI 3.80 to 9.09)
Starter
rng = np.random.default_rng(42)
n = 2_000
tenure = rng.uniform(0, 60, size=n)
# TODO: coupon from p_coupon with rng.random(n) < p_coupon
# TODO: spend = 40 + 1.5 * tenure + 5 * coupon + rng.normal(0, 15, size=n)
# TODO: naive and adjusted OLS; print coef and conf_int for "coupon"
# TODO: randomized coupons with rng.random(n) < 0.5; new spend; naive OLS
Hint 1

Store the variables in a DataFrame with coupon as 0/1 integers, so the formula API sees a number.

Hint 2

A small helper avoids repetition: def effect(formula, data) that fits and returns the coefficient and CI of coupon.

Hint 3

Draw in this order: tenure, coupon, observational noise, random coupons, new noise. The expected output depends on that order.

Solution
def effect(formula: str, data: pd.DataFrame) -> tuple[float, float, float]:
fit = smf.ols(formula, data=data).fit()
low, high = fit.conf_int().loc["coupon"]
return fit.params["coupon"], low, high
rng = np.random.default_rng(42)
n = 2_000
tenure = rng.uniform(0, 60, size=n)
p_coupon = 1 / (1 + np.exp(-(tenure - 30) / 8))
coupon = (rng.random(n) < p_coupon).astype(int)
spend = 40 + 1.5 * tenure + 5 * coupon + rng.normal(0, 15, size=n)
obs = pd.DataFrame({"tenure": tenure, "coupon": coupon, "spend": spend})
random_coupon = (rng.random(n) < 0.5).astype(int)
spend_rct = 40 + 1.5 * tenure + 5 * random_coupon + rng.normal(0, 15, size=n)
rct = pd.DataFrame({"tenure": tenure, "coupon": random_coupon, "spend": spend_rct})
results = {
"observational, naive": effect("spend ~ coupon", obs),
"observational, adjusted": effect("spend ~ coupon + tenure", obs),
"randomized, naive": effect("spend ~ coupon", rct),
}
for label, (coef, low, high) in results.items():
print(f"{label:<24} {coef:6.2f} USD (95% CI {low:6.2f} to {high:6.2f})")
assert results["observational, naive"][1] > 5
for label in ("observational, adjusted", "randomized, naive"):
assert results[label][1] < 5 < results[label][2]
Output
observational, naive 41.36 USD (95% CI 39.24 to 43.49)
observational, adjusted 4.21 USD (95% CI 2.36 to 6.06)
randomized, naive 6.44 USD (95% CI 3.80 to 9.09)

How it works:

  1. Tenure drives both coupon use and spend, so it is a confounder. The naive model credits the coupon with the spending of loyal customers: its estimate is about eight times the true 5 USD, and its CI excludes 5.
  2. Adding tenure to the model holds it fixed, and the estimate falls back to about 5 USD.
  3. With random coupons, tenure cannot influence who gets a coupon. The simple naive comparison is then unbiased, without any adjustment. This is why randomized experiments are the gold standard for causal questions.

Alternative: stratify instead of regressing. Cut tenure into 6 bins with pd.cut, compare coupon users with non-users inside each bin, and average the differences. It gives a similar answer and shows the idea of “comparing like with like”.

Challenge

Refactor: the procedural code below analyzes the whole test and then copies the same lines for the desktop segment. Rewrite it as a frozen dataclass ABTest with the four counts as fields, a class method from_frame(df), a lift property, a p_value() method, a lift_ci() method (Newcombe) and a decision(break_even) method that applies the decision table of the lesson. Print one report line for all users, desktop and mobile with a break-even of 0.5 percentage points.

Expected output
all lift +1.55 pp, p = 0.0129, CI +0.33 to +2.77 pp -> extend the test
desktop lift +2.46 pp, p = 0.0337, CI +0.19 to +4.73 pp -> extend the test
mobile lift +1.46 pp, p = 0.0603, CI -0.06 to +2.98 pp -> no evidence
Starter
from statsmodels.stats.proportion import confint_proportions_2indep, proportions_ztest
g = ab.groupby("group")["converted"].agg(["sum", "count"])
k_t, n_t = g.loc["treatment", "sum"], g.loc["treatment", "count"]
k_c, n_c = g.loc["control", "sum"], g.loc["control", "count"]
lift = k_t / n_t - k_c / n_c
p = proportions_ztest([k_t, k_c], [n_t, n_c])[1]
lo, hi = confint_proportions_2indep(k_t, n_t, k_c, n_c, method="newcomb")
print("all", round(100 * lift, 2), round(p, 4), round(100 * lo, 2), round(100 * hi, 2))
desk = ab[ab["device"] == "desktop"]
g = desk.groupby("group")["converted"].agg(["sum", "count"])
# ... the same eight lines again for desktop, then for mobile
# TODO: replace all of this with an ABTest dataclass
Hint 1

@dataclass(frozen=True) with fields k_t, n_t, k_c, n_c: int. The class method builds the counts with the groupby from the starter and calls cls(...).

Hint 2

decision checks the CI in order: lower end above the break-even → “launch”; lower end above 0 → “extend the test”; upper end below 0 → “do not launch”; otherwise “no evidence”.

Hint 3

Convert NumPy numbers to Python types with int() and float(), so the dataclass fields and the return values are plain numbers.

Solution
from dataclasses import dataclass
from typing import Self
from statsmodels.stats.proportion import confint_proportions_2indep, proportions_ztest
@dataclass(frozen=True)
class ABTest:
"""Conversion counts of a two-group test, with the standard analysis."""
k_t: int
n_t: int
k_c: int
n_c: int
@classmethod
def from_frame(cls, df: pd.DataFrame, metric: str = "converted") -> Self:
g = df.groupby("group")[metric].agg(["sum", "count"])
return cls(
int(g.loc["treatment", "sum"]), int(g.loc["treatment", "count"]),
int(g.loc["control", "sum"]), int(g.loc["control", "count"]),
)
@property
def lift(self) -> float:
return self.k_t / self.n_t - self.k_c / self.n_c
def p_value(self) -> float:
return float(proportions_ztest([self.k_t, self.k_c], [self.n_t, self.n_c])[1])
def lift_ci(self, alpha: float = 0.05) -> tuple[float, float]:
lo, hi = confint_proportions_2indep(
self.k_t, self.n_t, self.k_c, self.n_c, method="newcomb", alpha=alpha
)
return float(lo), float(hi)
def decision(self, break_even: float) -> str:
lo, hi = self.lift_ci()
if lo > break_even:
return "launch"
if lo > 0:
return "extend the test"
if hi < 0:
return "do not launch"
return "no evidence"
segments = {
"all": ab,
"desktop": ab[ab["device"] == "desktop"],
"mobile": ab[ab["device"] == "mobile"],
}
for name, df in segments.items():
test = ABTest.from_frame(df)
lo, hi = test.lift_ci()
print(f"{name:<8} lift {100 * test.lift:+.2f} pp, p = {test.p_value():.4f}, "
f"CI {100 * lo:+.2f} to {100 * hi:+.2f} pp -> {test.decision(0.005)}")
overall = ABTest.from_frame(ab)
assert (overall.k_t, overall.n_t, overall.k_c, overall.n_c) == (583, 4998, 506, 5002)
assert overall.decision(0.005) == "extend the test"
Output
all lift +1.55 pp, p = 0.0129, CI +0.33 to +2.77 pp -> extend the test
desktop lift +2.46 pp, p = 0.0337, CI +0.19 to +4.73 pp -> extend the test
mobile lift +1.46 pp, p = 0.0603, CI -0.06 to +2.98 pp -> no evidence

How it works:

  1. The dataclass holds the only data the analysis needs: four counts. frozen=True makes a test result immutable, so no later code can change the counts by accident.
  2. from_frame is an alternative constructor (module 18): it hides the groupby once, instead of in every copy.
  3. Each method does one job. Adding a segment is one dict entry instead of eight copied lines, and the decision rule lives in one place.
  4. The segment rows show why segment decisions need care: each segment is smaller, so its CI is wider and its decision weaker than the overall one.

Alternative: a plain function analyze(df) -> dict would also remove the duplication. A class pays off when several methods share the same data and you want to pass a test result around, compare tests or add methods later (relative_lift_ci, srm_p_value).

Challenge

The lesson planned 3,835 users per group to detect a lift from 10% to 12% with 80% power. Check it by simulation: run 4,000 experiments with rng = np.random.default_rng(42) (control first, then treatment, each with rng.binomial(n, p, size=4_000)), run the pooled z-test on each, and print the share with p≤0.05p \le 0.05. Compare it with NormalIndPower().power(...) and with the Monte Carlo standard error of the simulated power, P^(1−P^)/4000\sqrt{\hat{P}(1-\hat{P})/4000}.

Expected output
simulated power 0.799 (Monte Carlo SE 0.006)
analytical power 0.800
Starter
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize
rng = np.random.default_rng(42)
n, sims = 3_835, 4_000
# TODO: k_c and k_t with rng.binomial
# TODO: pooled z and two-sided p-values for all simulations at once
# TODO: simulated power, its Monte Carlo SE, and the analytical power
Hint 1

The z formula from the lesson works on arrays: pool = (k_c + k_t) / (2 * n).

Hint 2

NormalIndPower().power(effect_size=proportion_effectsize(0.12, 0.10), nobs1=n, alpha=0.05).

Solution
from statsmodels.stats.power import NormalIndPower
from statsmodels.stats.proportion import proportion_effectsize
rng = np.random.default_rng(42)
n, sims = 3_835, 4_000
k_c = rng.binomial(n, 0.10, size=sims)
k_t = rng.binomial(n, 0.12, size=sims)
pool = (k_c + k_t) / (2 * n)
z = (k_t / n - k_c / n) / np.sqrt(pool * (1 - pool) * 2 / n)
p = 2 * stats.norm.sf(np.abs(z))
sim_power = (p <= 0.05).mean()
mc_se = np.sqrt(sim_power * (1 - sim_power) / sims)
h = proportion_effectsize(0.12, 0.10)
analytic = NormalIndPower().power(effect_size=h, nobs1=n, alpha=0.05)
print(f"simulated power {sim_power:.3f} (Monte Carlo SE {mc_se:.3f})")
print(f"analytical power {analytic:.3f}")
assert abs(sim_power - analytic) < 3 * mc_se
Output
simulated power 0.799 (Monte Carlo SE 0.006)
analytical power 0.800

How it works:

  1. Each simulated experiment has a real 2-point lift, so every rejection is a correct detection. The share of rejections estimates the power.
  2. The simulated power has its own sampling error. With 4,000 simulations, its standard error is about 0.006, and the analytical value is well within three standard errors.
  3. Simulation is the general tool: it works for any test, any design and any metric, even where no power formula exists.

Alternative: vary n in a loop (for example 1,000 to 6,000 in steps of 500) and plot the simulated power against n. The result is a power curve, the standard chart for choosing a sample size.