29. Statistics and probability
Exploratory analysis (module 27) finds patterns: churners log in less, big houses cost more, a new checkout page seems to convert better. This module asks the next question: is the pattern real, or could chance alone produce it? Statistics gives you the tools to answer with numbers. You describe data, model randomness with probability distributions, estimate unknown quantities with a margin of error and test claims against the data.
Every analyst, data scientist and ML engineer uses these tools. A product team ships a feature only when the A/B test shows a real gain. A model’s accuracy is reported with a confidence interval. A regression coefficient is trusted only when its standard error is small.
What you will learn
Section titled “What you will learn”- Describe a variable by its center (mean, median, mode), spread (variance with
ddof, standard deviation, IQR) and shape (skewness). - Use the normal, binomial, Poisson and t distributions in
scipy.stats:pdf,pmf,cdf,sf,ppfandrvs. - Explain sampling distributions, the standard error and the central limit theorem, and see them in a simulation.
- Build confidence intervals for a mean, a proportion and any statistic (with the bootstrap), and read them correctly.
- Run and interpret hypothesis tests (t-tests, chi-square, ANOVA, Kruskal–Wallis, Mann–Whitney U), check their assumptions (Q-Q plots, Levene’s test, residual plots), and report p-values, effect sizes, power and corrections for multiple tests.
- Analyze an A/B test from start to finish, tell correlation from causation and read a statsmodels OLS regression.
Prerequisites
Section titled “Prerequisites”- 23. NumPy: arrays, vectorized math and
np.random.default_rng. - 24. pandas fundamentals and 25. pandas advanced: selecting,
groupby,crosstabandpivot_table. - 27. Exploratory data analysis: distributions, outliers and correlation.
- 28. Visualization: Matplotlib figures and axes.
- 09. Standard library power tools: the
statisticsmodule, seeds and a first bootstrap. - The course datasets in a
data/folder: Get the data. SciPy and statsmodels come with the course environment.
You need no prior statistics. The lesson defines every term. High-school algebra is enough for the formulas.
Concepts
Section titled “Concepts”All code on this page runs in one session. The first block imports the libraries and fixes how pandas prints:
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport scipyimport statsmodelsimport statsmodels.formula.api as smffrom scipy import stats
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)print("scipy", scipy.__version__, "| statsmodels", statsmodels.__version__)scipy 1.18.1 | statsmodels 0.15.0SciPy is the scientific-computing library of Python. Its scipy.stats module holds probability distributions and statistical tests. statsmodels adds statistical models, such as regression, with detailed output for inference, plus tools for power analysis and proportions.
Populations, samples and statistics
Section titled “Populations, samples and statistics”A population is the whole group that you want to know about: every customer of the company, every visitor who will ever see the checkout page. A sample is the part of the population that you actually observe. You almost never see the whole population, so you learn about it from a sample.
A number that describes the population is a parameter, for example the true churn rate of all customers. A number that you compute from a sample is a statistic, for example the churn rate of the 400 customers that you surveyed. Statistics estimate parameters. Different samples give different statistics, so every estimate carries uncertainty.
| Population parameter | Sample statistic | |
|---|---|---|
| Mean | (mu) | (x-bar) |
| Standard deviation | (sigma) | |
| Proportion | (p-hat) | |
| Size |
A random sample gives every member of the population the same chance to be chosen. Only a random sample lets you use the formulas of this module. A sample that systematically favors some members has sampling bias: a survey sent only to customers who log in often says nothing reliable about churners.
The field has two halves:
- Descriptive statistics summarize the data you have: the average, the spread, the shape.
- Inferential statistics draw conclusions about the population from a sample, with a stated uncertainty: confidence intervals and hypothesis tests.
A stratified sample first splits the population into groups, called strata, then draws a random sample inside each stratum in the same proportion. Every group then appears in its true share, which makes estimates a little more precise. scikit-learn’s train_test_split(..., stratify=y) uses the same idea (module 34). Compare a simple random sample of 200 customers with a sample stratified by contract type:
customers = pd.read_csv("data/customers.csv")simple = customers.sample(n=200, random_state=42)strat = customers.groupby("contract").sample(frac=0.04, random_state=42)frames = {"population": customers, "simple": simple, "stratified": strat}for name, df in frames.items(): shares = df["contract"].value_counts(normalize=True).sort_index().round(3) print(f"{name:<10} n={len(df):<5} {shares.to_dict()}")
rng = np.random.default_rng(42)est_simple, est_strat = [], []for _ in range(500): # 500 repeated surveys of each kind seed = int(rng.integers(1_000_000)) est_simple.append(customers.sample(n=200, random_state=seed)["churned"].mean()) by_contract = customers.groupby("contract").sample(frac=0.04, random_state=seed) est_strat.append(by_contract["churned"].mean())print(f"sd of the churn-rate estimate: simple {np.std(est_simple):.4f}" f" | stratified {np.std(est_strat):.4f}")population n=5000 {'month-to-month': 0.557, 'one-year': 0.245, 'two-year': 0.198}simple n=200 {'month-to-month': 0.56, 'one-year': 0.25, 'two-year': 0.19}stratified n=200 {'month-to-month': 0.555, 'one-year': 0.245, 'two-year': 0.2}sd of the churn-rate estimate: simple 0.0263 | stratified 0.0233groupby("contract").sample(frac=0.04) draws 4% of each contract type, so the stratified sample matches the population shares up to rounding. Contract type is strongly related to churn, so fixing its mix removes one source of chance variation: over 500 repeated surveys, the stratified estimate of the churn rate varies less.
This lesson uses one trick often. data/customers.csv has 5,000 customers (see the data dictionary for every column). For some demonstrations, it plays the role of the whole population. You draw small samples from it and check the estimates against the “true” values, which real life never lets you see.
Measures of center: mean, median and mode
Section titled “Measures of center: mean, median and mode”The mean is the sum of the values divided by their count:
The median is the middle value after sorting: half the values are below it and half above. The mode is the most frequent value. It is useful for discrete values and categories, not for continuous prices.
houses = pd.read_csv("data/houses.csv")price = houses["price"]print(f"mean {price.mean():>11,.1f}")print(f"median {price.median():>11,.1f}")print("most common bedroom count:", houses["bedrooms"].mode().tolist())print("formula check:", price.sum() / len(price) == price.mean())mean 476,465.5median 376,000.0most common bedroom count: [3]formula check: TrueThe mean house price is far above the median. A few very expensive houses pull the mean up, but they move the median only a little. mode() returns a Series, because a column can have several modes, so the code converts it to a list.
Which one to report:
| Data | Report | Why |
|---|---|---|
| Symmetric, no extreme values (sensor readings) | mean | uses every value; most efficient |
| Skewed or with outliers (prices, incomes, revenue) | median (and the mean, if totals matter) | robust: a few extreme values barely move it |
| Categories or small counts (plan, bedrooms) | mode | the only center that works for labels |
A statistic is robust when a few extreme values cannot move it much. The median is robust; the mean is not. But the mean has one property that the median lacks: mean × count = total. Revenue planning needs totals, so it needs the mean.
Measures of spread: variance, standard deviation and IQR
Section titled “Measures of spread: variance, standard deviation and IQR”Two products can have the same mean revenue and very different risk. Spread measures how far values scatter around the center.
The variance is the average squared distance from the mean. The standard deviation is its square root, so it has the same unit as the data. For a sample, divide by instead of :
The number you subtract from is called ddof (“delta degrees of freedom”). Degrees of freedom are the number of values that are free to vary after you fix a statistic. Once you know , only deviations are free: the last one is forced, because the deviations sum to 0. So ddof=1 gives the sample variance and ddof=0 gives the population variance.
The libraries disagree on the default. This is a classic source of small, confusing differences:
x = np.array([19.5, 20.7, 20.1, 21.2, 21.2, 20.8]) # six sensor readingsprint("numpy np.var(x) ", round(np.var(x), 4)) # ddof=0 by defaultprint("numpy np.var(x, ddof=1)", round(np.var(x, ddof=1), 4))print("pandas Series.var() ", round(pd.Series(x).var(), 4)) # ddof=1 by defaultprint("manual sum / (n - 1) ", round(((x - x.mean()) ** 2).sum() / (len(x) - 1), 4))print("std, ddof=1 ", round(np.std(x, ddof=1), 4))numpy np.var(x) 0.3714numpy np.var(x, ddof=1) 0.4457pandas Series.var() 0.4457manual sum / (n - 1) 0.4457std, ddof=1 0.6676Why ? The sample mean sits in the middle of the sample by construction, so distances to are a little smaller than distances to the true . Dividing by underestimates the true variance. A quick simulation shows it: draw 20,000 samples of 5 values from a distribution whose true variance is 1.
rng = np.random.default_rng(42)samples = rng.normal(loc=0, scale=1, size=(20_000, 5)) # 20,000 samples of n = 5print("average ddof=0 variance:", samples.var(axis=1, ddof=0).mean().round(3))print("average ddof=1 variance:", samples.var(axis=1, ddof=1).mean().round(3))average ddof=0 variance: 0.805average ddof=1 variance: 1.007On average, ddof=0 gives about of the truth; ddof=1 is right on average. An estimator that is right on average is unbiased. With thousands of rows, the difference is negligible. With 5 or 10 values, it matters.
The interquartile range (IQR) is the distance between the first quartile (25th percentile) and the third quartile (75th percentile). It covers the middle half of the data, so, like the median, it is robust:
q1, q3 = price.quantile([0.25, 0.75])print(f"Q1 {q1:,.0f} Q3 {q3:,.0f} IQR {q3 - q1:,.0f}")print(f"scipy iqr {stats.iqr(price):,.0f}")print(f"std {price.std():,.0f}")print(f"range {price.max() - price.min():,.0f}")Q1 278,500 Q3 560,375 IQR 281,875scipy iqr 281,875std 318,751range 3,613,000The standard deviation is larger than the IQR here, because squaring makes the extreme prices count a lot. Report the median with the IQR, and the mean with the standard deviation. Module 26 used the IQR to flag outliers: values beyond or .
Shape: skewness and kurtosis
Section titled “Shape: skewness and kurtosis”Skewness measures how lopsided a distribution is. Skewness 0 means symmetric. Positive skewness (right skew) means a long tail of large values, as with prices, incomes and order revenue. Negative skewness means a long tail of small values, as with exam scores near a ceiling.
Kurtosis measures how heavy the tails are. pandas and SciPy report excess kurtosis: 0 for the normal distribution, positive for heavier tails (more extreme values than a normal distribution predicts).
print("skew of price: ", round(price.skew(), 3))print("skew of log price:", round(np.log(price).skew(), 3))print("excess kurtosis: ", round(price.kurt(), 3))print("scipy skew (biased formula):", round(stats.skew(price), 3))skew of price: 2.666skew of log price: 0.699excess kurtosis: 11.036scipy skew (biased formula): 2.665| Skewness | Reading | Typical data |
|---|---|---|
| about −0.5 to 0.5 | roughly symmetric | measurement errors, heights, log prices |
| 0.5 to 1 (or −0.5 to −1) | moderately skewed | session times |
| above 1 (or below −1) | strongly skewed | prices, revenue, counts of rare events |
The log of price is much more symmetric. Taking logs is the standard fix for right-skewed money data: it turns multiplicative effects (“+10%”) into additive ones. pandas skew() uses a small-sample correction, while scipy.stats.skew uses the plain formula by default (bias=True). With 3,000 rows, the two agree to two decimals.
Random variables and probability distributions
Section titled “Random variables and probability distributions”A random variable is a quantity whose value depends on chance: the number of buyers among the next 200 visitors, the temperature reading of the next minute. A probability distribution says which values the random variable can take and how likely each one is.
- A discrete random variable takes separate values that you can count: 0, 1, 2 buyers. Its probability mass function (PMF) gives the probability of each value, .
- A continuous random variable can take any value in a range: 21.37 °C. Any single exact value has probability 0, so you use a probability density function (PDF). The area under the PDF between two points is the probability of landing between them.
Three more functions work for both kinds:
- The cumulative distribution function (CDF) gives : the probability of a value at most .
- The survival function (SF) gives . It is more precise than
1 - cdffor tiny tail probabilities. - The percent point function (PPF), also called the quantile function, is the inverse of the CDF. It answers: “below which value do 95% of outcomes fall?”
In scipy.stats, every distribution is an object with these methods. You set its parameters once and get a frozen distribution:
| Method | Returns | Example question |
|---|---|---|
pmf(k) |
, discrete only | chance of exactly 20 buyers |
pdf(x) |
density at x, continuous only |
height of the bell curve at 21 °C |
cdf(x) |
chance of at most 15 buyers | |
sf(x) |
chance of more than 30 orders | |
ppf(q) |
the value with cdf = q |
99th percentile of the reading |
interval(c) |
the central range holding probability c |
range of 95% of readings |
mean(), std(), var() |
moments of the distribution | expected buyers |
rvs(size, random_state) |
random draws | simulate 1,000 days |
The normal distribution
Section titled “The normal distribution”The normal distribution (also called Gaussian) is the symmetric bell curve. Two parameters define it: the mean (the center) and the standard deviation (the width). Its density is:
Measurement noise is often close to normal. Suppose the server-room sensor reads the true temperature of 21.0 °C plus noise with °C. In SciPy, loc is the mean and scale is the standard deviation:
reading = stats.norm(loc=21.0, scale=0.5)print("density at 21.0: ", round(reading.pdf(21.0), 4))print("formula at 21.0: ", round(1 / (0.5 * np.sqrt(2 * np.pi)), 4))print("P(reading <= 20.0): ", round(reading.cdf(20.0), 4))print("P(reading > 22.0): ", round(reading.sf(22.0), 4))print("99th percentile: ", round(reading.ppf(0.99), 3))print("central 95% range: ", np.round(reading.interval(0.95), 3))print("5 simulated readings: ", reading.rvs(size=5, random_state=42).round(2))density at 21.0: 0.7979formula at 21.0: 0.7979P(reading <= 20.0): 0.0228P(reading > 22.0): 0.022899th percentile: 22.163central 95% range: [20.02 21.98]5 simulated readings: [21.25 20.93 21.32 21.76 20.88]random_state=42 makes the random draws repeatable. A reading above 22.0 °C is two standard deviations above the mean, so it happens only about 2.3% of the time. An alert rule “warn above 22 °C” would therefore fire on about 1 reading in 44 even when nothing is wrong.
The standard normal distribution has and . Any normal value converts to it with the z-score from module 18. Its probabilities give the 68–95–99.7 rule:
z = stats.norm() # the standard normal: loc=0, scale=1for k in (1, 2, 3): print(f"within {k} sd: {z.cdf(k) - z.cdf(-k):.4f}")print("z for a two-sided 95% range:", round(z.ppf(0.975), 4))within 1 sd: 0.6827within 2 sd: 0.9545within 3 sd: 0.9973z for a two-sided 95% range: 1.96The number 1.96 appears all over statistics: 95% of a normal distribution lies within 1.96 standard deviations of the mean.
The binomial distribution
Section titled “The binomial distribution”The binomial distribution counts successes in independent trials that each succeed with the same probability : buyers among 200 visitors, churners among 50 customers, defective items in a batch of 100. A trial with two outcomes is a Bernoulli trial.
(“n choose k”) is the number of ways to pick which of the trials succeed (module 09 computed it with math.comb).
The checkout page converts about 10% of visitors. What happens on a day with 200 visitors?
from math import comb
buyers = stats.binom(n=200, p=0.10)print("expected buyers:", buyers.mean(), "| sd:", round(buyers.std(), 3))print("P(exactly 20): ", round(buyers.pmf(20), 4))print("formula: ", round(comb(200, 20) * 0.10**20 * 0.90**180, 4))print("P(at most 15): ", round(buyers.cdf(15), 4))print("P(30 or more): ", round(buyers.sf(29), 4))print("simulated days: ", buyers.rvs(size=8, random_state=42))expected buyers: 20.0 | sd: 4.243P(exactly 20): 0.0936formula: 0.0936P(at most 15): 0.1431P(30 or more): 0.0163simulated days: [19 27 23 21 16 16 14 25]Even with a fixed 10% rate, the eight simulated days range from 14 to 27 buyers. A day with 15 or fewer buyers happens about one day in seven by chance alone. Note sf(29) for “30 or more”: for a discrete variable, .
The Poisson distribution
Section titled “The Poisson distribution”The Poisson distribution counts events in a fixed interval when events arrive independently at a constant average rate (lambda): orders per day, support tickets per hour, errors per million requests.
The store chain gets about 20.35 orders per day. If orders were Poisson, how often would a day bring more than 30 orders? Compare the model with the real days in data/sales.csv:
from math import factorial
sales = pd.read_csv("data/sales.csv")orders_per_day = sales.groupby("order_date")["order_id"].nunique()lam = orders_per_day.mean()orders = stats.poisson(mu=lam)print(f"mean {lam:.2f} | variance {orders_per_day.var():.2f}")print(f"Poisson P(> 30 orders): {orders.sf(30):.4f}")print(f"observed share > 30: {(orders_per_day > 30).mean():.4f}")k = 25pmf_formula = lam**k * np.exp(-lam) / factorial(k)print(f"P(X = 25): scipy {orders.pmf(k):.5f} | formula {pmf_formula:.5f}")mean 20.35 | variance 104.04Poisson P(> 30 orders): 0.0167observed share > 30: 0.0985P(X = 25): scipy 0.04850 | formula 0.04850The Poisson model says the variance should equal the mean. The real variance is about five times larger, and busy days are six times more common than the model predicts. The rate is not constant: weekends, December and Black Friday push it up. Data whose variance exceeds its Poisson mean is overdispersed. A distribution is a model. Always check it against the data before you trust its tail probabilities. Per hour on an ordinary Tuesday, the Poisson model would fit much better.
Student’s t distribution
Section titled “Student’s t distribution”The t distribution (Student’s t) looks like the standard normal, but with heavier tails. It appears when you standardize a sample mean with the sample standard deviation instead of the unknown . Estimating adds uncertainty, and the heavier tails account for it. One parameter, the degrees of freedom (df), sets the shape. For a sample of values, df . As df grows, the t distribution approaches the normal.
print("df t critical value (two-sided 95%)")for df in (4, 9, 29, 99, 999): print(f"{df:<6} {stats.t(df).ppf(0.975):.4f}")print(f"normal {stats.norm.ppf(0.975):.4f}")df t critical value (two-sided 95%)4 2.77649 2.262229 2.045299 1.9842999 1.9623normal 1.9600With 5 values (df = 4), a 95% interval must reach 2.78 standard errors instead of 1.96. With 100 or more values, t and normal are almost the same. You can also call a method on the distribution class directly, as in stats.norm.ppf(0.975), instead of freezing it first.
| Distribution | Kind | Parameters (scipy) | Models |
|---|---|---|---|
| Normal | continuous | loc = μ, scale = σ |
measurement noise, sums and averages of many values |
| Binomial | discrete | n, p |
successes in n yes/no trials |
| Poisson | discrete | mu = λ |
event counts per interval |
| t | continuous | df (also loc, scale) |
standardized means with estimated σ |
| Uniform | continuous | loc = low, scale = width |
“any value equally likely” |
| Exponential | continuous | scale = 1/λ |
waiting time between Poisson events |
| Log-normal | continuous | s = σ of log, scale = |
prices, revenue of buyers |
Sampling distributions and the standard error
Section titled “Sampling distributions and the standard error”Imagine running the same survey many times, each time with a new random sample of 50 customers. Each survey gives a different sample mean. The distribution of those means is the sampling distribution of the mean. Its standard deviation is the standard error (SE). Module 09 met the term; here is its formula:
The standard error tells you how far a sample mean typically lands from the true mean. It shrinks with : to halve the error, you need four times as many observations.
Treat the 5,000 customers as the population and check the formula by simulation:
customers = pd.read_csv("data/customers.csv")charges = customers["monthly_charges"].to_numpy()sigma = charges.std() # population sd: the whole "population" is known hererng = np.random.default_rng(42)for n in (25, 100, 400): means = rng.choice(charges, size=(2_000, n)).mean(axis=1) # 2,000 surveys of size n print(f"n={n:<4} sd of 2,000 sample means {means.std():.3f}" f" | sigma/sqrt(n) {sigma / np.sqrt(n):.3f}")n=25 sd of 2,000 sample means 4.543 | sigma/sqrt(n) 4.587n=100 sd of 2,000 sample means 2.289 | sigma/sqrt(n) 2.293n=400 sd of 2,000 sample means 1.164 | sigma/sqrt(n) 1.147The simulated spread of the sample means matches , and it halves each time quadruples. The law of large numbers is the companion result: as grows, the sample mean gets closer and closer to the true mean.
The central limit theorem
Section titled “The central limit theorem”The central limit theorem (CLT) says: for large enough samples, the sampling distribution of the mean is approximately normal, whatever the shape of the original data, as long as the data has a finite variance and the observations are independent. The mean of that normal curve is and its standard deviation is .
This is why the normal and t distributions appear in tests about means of very non-normal data, such as revenue. “Large enough” depends on the skew: about 30 values for mildly skewed data, a few hundred for heavy right tails. Example 2 shows the CLT at work on order revenue, with a histogram.
Confidence intervals
Section titled “Confidence intervals”A point estimate, such as “mean monthly charge 63.58 USD”, hides its uncertainty. A confidence interval (CI) gives a range of plausible values for the parameter. Module 09 built one with the bootstrap. Here are the three standard methods.
t-interval for a mean. The sample mean, plus or minus a margin of error: a critical value from the t distribution times the standard error:
Interval for a proportion. The simplest is the Wald interval, . It is poor for small samples or proportions near 0 or 1: it can even go below 0. The Wilson interval fixes this and is the recommended default. statsmodels computes both with proportion_confint.
Bootstrap interval for any statistic. Resample the data with replacement many times, compute the statistic on each resample and take the middle 95% of the results (or a refined version, BCa). It works for medians, ratios and other statistics that have no simple formula. scipy.stats.bootstrap does it.
What “95% confidence” means: if you repeated the whole procedure (sample, compute the interval) many times, about 95% of the intervals would contain the true parameter. Coverage is that long-run share. It does not mean “the parameter has a 95% probability to be in this particular interval”: the parameter is fixed, and this interval either contains it or not. Example 3 checks the coverage by simulation.
| Interval | Use for | Python |
|---|---|---|
| t-interval | a mean | stats.ttest_1samp(x, 0).confidence_interval() or stats.t.interval |
| Wilson | a proportion | proportion_confint(k, n, method="wilson") |
| Newcombe / Wald | a difference of two proportions | confint_proportions_2indep(k1, n1, k2, n2) |
| Welch | a difference of two means | stats.ttest_ind(a, b, equal_var=False).confidence_interval() |
| Bootstrap (BCa or percentile) | a median, ratio, any statistic | stats.bootstrap((x,), np.median, rng=rng) |
A higher confidence level (99% instead of 95%) gives a wider interval. A larger sample gives a narrower one.
The hypothesis-testing framework
Section titled “The hypothesis-testing framework”The new checkout page converted 11.66% of its visitors; the old one converted 10.12%. Is the new page better, or did the random split of users just happen to put more buyers in the treatment group? A hypothesis test answers this question in a fixed way.
- State the null hypothesis : the boring explanation, “no effect, no difference”. Here: both pages have the same true conversion rate.
- State the alternative hypothesis : what you suspect. Here: the rates differ. A two-sided alternative (“differ”) is the default. A one-sided alternative (“the new page is better”) is allowed only when you decided it before you saw the data and a change in the other direction would lead to the same action.
- Choose the significance level (alpha), the false-alarm rate that you accept, before you look. The usual value is 0.05.
- Compute a test statistic: one number that measures how far the data is from , such as a z or t value.
- Find the null distribution: the distribution of the test statistic if were true.
- Compute the p-value and compare it with .
flowchart LR
Q["Question"] --> H["H0 and H1<br/>choose alpha"]
H --> D["Collect data"]
D --> T["Test statistic"]
T --> P["p-value from the<br/>null distribution"]
P --> R{"p <= alpha?"}
R -->|yes| S["Reject H0<br/>report effect + CI"]
R -->|no| F["Fail to reject H0<br/>report CI and power"]
The p-value, precisely: the probability, computed under the assumption that is true (and that the test’s assumptions hold), of a test statistic at least as extreme as the one you observed. A small p-value says: “if there were no effect, data like this would be rare”. If , you reject and call the result statistically significant. If , you fail to reject . You never “accept” it.
You can build the null distribution yourself with a permutation test. If the page has no effect, the group labels are arbitrary. So shuffle the labels many times, and recompute the difference each time. The shuffled differences show what chance alone produces:
ab = pd.read_csv("data/ab_test.csv")is_treatment = (ab["group"] == "treatment").to_numpy()converted = ab["converted"].to_numpy()observed = converted[is_treatment].mean() - converted[~is_treatment].mean()
rng = np.random.default_rng(42)null_diffs = np.empty(5_000)for i in range(5_000): shuffled = rng.permutation(is_treatment) # random relabeling under H0 null_diffs[i] = converted[shuffled].mean() - converted[~shuffled].mean()
p_perm = (np.abs(null_diffs) >= abs(observed)).mean() # two-sidedprint(f"observed difference: {observed:.4f}")print(f"sd of null differences: {null_diffs.std():.4f}")print(f"permutation p-value: {p_perm:.4f}")observed difference: 0.0155sd of null differences: 0.0062permutation p-value: 0.0132fig, ax = plt.subplots(figsize=(8, 4))ax.hist(null_diffs, bins=30, color="#9aa5b1", edgecolor="white")for x in (observed, -observed): ax.axvline(x, color="#c0392b", linestyle="--")ax.set_title("Differences in conversion when the group labels are shuffled")ax.set_xlabel("treatment rate - control rate")ax.set_ylabel("shuffles")ax.text(observed, ax.get_ylim()[1] * 0.9, " observed", color="#c0392b")plt.show()
Only about 1.3% of the shuffles produce a difference as large as the real one. The p-value is about 0.013. That is below 0.05, so you reject : chance alone rarely produces a gap this large. Example 6 gets the same answer with a z-test formula.
Common misreadings of the p-value. Each sentence below is wrong:
| Wrong reading | Why it is wrong |
|---|---|
| “p = 0.013 means a 1.3% chance that is true.” | The p-value assumes is true. It cannot be the probability of . |
| “1 − p = 98.7% chance that the new page is better.” | Same error, the other way around. |
| “p = 0.013 means a 1.3% chance that the result is a fluke.” | It is the chance of data this extreme if there is no effect, not the chance that there is no effect. |
| “A small p-value means a big effect.” | With huge samples, tiny effects get tiny p-values. Report the effect size and its CI. |
| “p = 0.30, so there is no effect.” | Absence of evidence is not evidence of absence. The test may lack power. |
| “p = 0.049 is a finding; p = 0.051 is not.” | The two give almost the same evidence. 0.05 is a convention, not a law of nature. |
| “p is the false-positive rate of my test.” | is the false-positive rate, fixed in advance. p is a property of this data set. |
Type I and Type II errors
Section titled “Type I and Type II errors”A test can be wrong in two ways:
| true (no real effect) | false (real effect) | |
|---|---|---|
| Reject | Type I error (false positive), probability | correct: probability = power |
| Fail to reject | correct | Type II error (false negative), probability |
A Type I error ships a useless feature. A Type II error throws away a good one. You control directly. You control through the sample size (see Power and sample size).
An A/A test splits users into two groups that see the same page. Every significant result is then a false positive. Simulate 2,000 A/A tests with 5,000 users per group and a true rate of 10%:
rng = np.random.default_rng(42)n = 5_000buyers_a = rng.binomial(n, 0.10, size=2_000) # 2,000 tests, both groups identicalbuyers_b = rng.binomial(n, 0.10, size=2_000)p_a, p_b = buyers_a / n, buyers_b / np_pool = (buyers_a + buyers_b) / (2 * n)z_aa = (p_b - p_a) / np.sqrt(p_pool * (1 - p_pool) * (2 / n))p_values = 2 * stats.norm.sf(np.abs(z_aa))print(f"share of A/A tests with p <= 0.05: {(p_values <= 0.05).mean():.3f}")print(f"share with p <= 0.01: {(p_values <= 0.01).mean():.3f}")share of A/A tests with p <= 0.05: 0.051share with p <= 0.01: 0.010About 5% of the tests are “significant” at , and about 1% at 0.01, exactly as designed. Under , p-values are spread evenly between 0 and 1. That is the meaning of : the false-alarm rate when nothing is going on.
Choosing a test
Section titled “Choosing a test”| Question | Data | Parametric test | Nonparametric or exact alternative |
|---|---|---|---|
| Does one mean equal a target? | one numeric sample | one-sample t-test ttest_1samp |
Wilcoxon signed-rank wilcoxon |
| Do two groups differ? | numeric, two independent groups | Welch t-test ttest_ind(equal_var=False) |
Mann–Whitney U mannwhitneyu |
| Did the same units change? | numeric, paired (before/after) | paired t-test ttest_rel |
Wilcoxon signed-rank wilcoxon |
| Do 3+ groups differ? | numeric, 3+ independent groups | one-way ANOVA f_oneway |
Kruskal–Wallis kruskal |
| Do two proportions differ? | 0/1 outcome, two groups | two-proportion z-test proportions_ztest |
Fisher exact fisher_exact (small counts) |
| Are two categorical variables related? | contingency table | chi-square chi2_contingency |
Fisher exact (2×2, small counts) |
| Do counts match expected shares? | one categorical variable | chi-square goodness of fit chisquare |
exact multinomial test |
| Are two numeric variables related? | two numeric columns | Pearson pearsonr |
Spearman spearmanr |
The Wilcoxon signed-rank test ranks the sizes of the differences (from a target, or within pairs) and checks whether positive and negative differences balance. Fisher’s exact test computes the exact probability of a 2×2 table with the observed row and column totals, so it needs no large-count approximation.
A parametric test assumes a model for the data, such as normal means. A nonparametric test makes weaker assumptions, usually by working with ranks. It is safer with outliers, strong skew and ordinal scales, at the cost of a little power when the parametric assumptions hold.
t-tests
Section titled “t-tests”A t-test compares means. Its statistic is “difference divided by its standard error”, and its null distribution is a t distribution.
One-sample t-test. The product team claims that customers log in 12 times per 30 days on average. Test the claim with a survey of 50 random customers:
survey = customers.sample(n=50, random_state=42) # a random sample of 50logins = survey["logins_last_30d"]result = stats.ttest_1samp(logins, popmean=12)t_manual = (logins.mean() - 12) / (logins.std(ddof=1) / np.sqrt(len(logins)))print( f"sample mean {logins.mean():.2f}, t = {result.statistic:.3f}" f", manual t = {t_manual:.3f}")print(f"df = {result.df}, p = {result.pvalue:.3f}")ci = result.confidence_interval(confidence_level=0.95)print(f"95% CI for the mean: {ci.low:.2f} to {ci.high:.2f}")print(f"population mean: {customers['logins_last_30d'].mean():.2f}")sample mean 12.34, t = 0.457, manual t = 0.457df = 49, p = 0.65095% CI for the mean: 10.84 to 13.84population mean: 11.74The p-value is large, so the data gives no reason to doubt the claim. The confidence interval says more: the true mean is plausibly anywhere from about 10.8 to 13.8 logins. The full population mean (11.7) is inside, as you would hope.
Welch two-sample t-test. It compares the means of two independent groups. It does not assume that the groups have the same variance:
The older Student’s t-test (equal_var=True, the SciPy default) assumes equal variances. Welch’s version loses almost nothing when the variances are equal and stays correct when they are not. Always pass equal_var=False. Did the new checkout page change the time users spend on the page?
treat_time = ab.loc[ab["group"] == "treatment", "time_on_page_s"]ctrl_time = ab.loc[ab["group"] == "control", "time_on_page_s"]welch = stats.ttest_ind(treat_time, ctrl_time, equal_var=False)se = np.sqrt(treat_time.var() / len(treat_time) + ctrl_time.var() / len(ctrl_time))diff = treat_time.mean() - ctrl_time.mean()print(f"difference {diff:.2f} s, t = {welch.statistic:.2f}, manual t = {diff / se:.2f}")print(f"Welch df = {welch.df:.1f}, p = {welch.pvalue:.2e}")ci = welch.confidence_interval()print(f"95% CI for the difference: {ci.low:.2f} to {ci.high:.2f} s")difference 9.03 s, t = 8.48, manual t = 8.48Welch df = 9989.3, p = 2.55e-1795% CI for the difference: 6.95 to 11.12 sTreatment users stay about 9 seconds longer, and the interval excludes 0 by a wide margin. The :.2e format prints a tiny p-value in scientific notation. Welch’s degrees of freedom are not a whole number: they come from a formula that weighs the two variances.
Paired t-test. Sometimes the two measurements belong to the same unit: each store’s revenue in 2023 and in 2024, a patient before and after a treatment. Then you test the differences within each unit. That removes the large differences between units from the noise:
sales["year"] = sales["order_date"].str[:4]by_store = sales.pivot_table( index="store_id", columns="year", values="revenue", aggfunc="sum")paired = stats.ttest_rel(by_store["2024"], by_store["2023"])unpaired = stats.ttest_ind(by_store["2024"], by_store["2023"], equal_var=False)growth = by_store["2024"] - by_store["2023"]print(f"mean growth per store: {growth.mean():,.0f} USD")print(f"paired t-test: t = {paired.statistic:.2f}, p = {paired.pvalue:.6f}")print(f"unpaired (wrong): t = {unpaired.statistic:.2f}, p = {unpaired.pvalue:.3f}")print(f"one-sample on differences: p = {stats.ttest_1samp(growth, 0).pvalue:.6f}")print("every store grew:", bool((growth > 0).all()))mean growth per store: 25,445 USDpaired t-test: t = 6.97, p = 0.000024unpaired (wrong): t = 1.27, p = 0.218one-sample on differences: p = 0.000024every store grew: TrueEvery one of the 12 stores grew, so the paired test is very sure. The unpaired test sees only two clouds of store totals that overlap a lot, because big stores and small stores differ by far more than one year of growth. The paired t-test is exactly a one-sample t-test on the differences.
Assumptions of t-tests: independent observations (or independent pairs), and sample means that are close to normal. Thanks to the CLT, the second holds for moderate samples even with skewed data. With small, heavily skewed samples, use the nonparametric alternative or the bootstrap.
Checking assumptions
Section titled “Checking assumptions”A p-value is only as good as the assumptions behind it. Check them with plots first and tests second. Independence comes from the design of the study (random sampling, one row per customer); no test on the data can prove it.
Normality. A Q-Q plot (quantile-quantile plot) plots the sorted data against the quantiles that a normal distribution of the same size would give. Normal data lies on a straight line. A curve that bends upward at the right end shows a long right tail. stats.probplot computes the points and the correlation of the straight-line fit:
fig, axes = plt.subplots(1, 2, figsize=(10, 4))for ax, (label, values) in zip( axes, {"price": price, "log price": np.log(price)}.items(), strict=True): (osm, osr), (slope, intercept, r) = stats.probplot(values, dist="norm") ax.scatter(osm, osr, s=5, color="#4c78a8") ax.plot(osm, slope * osm + intercept, color="#c0392b") ax.set(title=f"Q-Q plot: {label}", xlabel="normal quantiles", ylabel="data") shapiro_p = stats.shapiro(values).pvalue print(f"{label:<9} r = {r:.4f} | Shapiro-Wilk p = {shapiro_p:.1e}")fig.tight_layout()plt.show()price r = 0.8662 | Shapiro-Wilk p = 2.4e-55log price r = 0.9838 | Shapiro-Wilk p = 2.0e-25
The raw prices bend away from the line at the top: the right tail is much longer than a normal tail. Log prices lie much closer to the line, but they still form a gentle S: the lowest values are higher than a normal distribution predicts (a short left tail) and the highest values are higher too (a longer right tail). That matches their skew of 0.70. The Shapiro–Wilk test (stats.shapiro) tests : “the data is normal”. With 3,000 rows, it rejects even the small departure of log prices, so it is not useful here. With large samples, normality tests flag harmless departures. With small samples, they miss serious ones. Read the plot, and remember that for tests of means the CLT matters more than the shape of the data.
Equal variances. Student’s t-test and ANOVA assume equal variances in the groups. Levene’s test (stats.levene) tests : “all groups have the same variance”. It compares the absolute distances from each group’s center, so it is robust to non-normal data:
print(f"time on page sd: treatment {treat_time.std():.1f}" f", control {ctrl_time.std():.1f}")print(f"Levene p = {stats.levene(treat_time, ctrl_time).pvalue:.3f}")churned_mask = customers["churned"] == 1charges_churn = customers.loc[churned_mask, "monthly_charges"]charges_stay = customers.loc[~churned_mask, "monthly_charges"]print(f"monthly charges sd: churners {charges_churn.std():.1f}" f", stayers {charges_stay.std():.1f}")print(f"Levene p = {stats.levene(charges_churn, charges_stay).pvalue:.1e}")time on page sd: treatment 54.0, control 52.5Levene p = 0.184monthly charges sd: churners 25.7, stayers 22.0Levene p = 4.8e-16The time-on-page groups have similar spreads. The charges of churners spread much more than those of stayers, and Levene’s test rejects equal variances. This is the case where Student’s t-test gives wrong p-values and Welch’s test stays correct. Because Welch’s test works in both cases, use it by default and skip the pre-test.
The chi-square test of independence
Section titled “The chi-square test of independence”A contingency table (a crosstab) counts the rows for each combination of two categorical variables. The chi-square test of independence asks if the two variables are related. Under (independence), each cell should hold its expected frequency:
is the observed count, the number of rows and the number of columns. Is churn related to autopay?
table = pd.crosstab(customers["has_autopay"], customers["churned"])print(table)expected = np.outer(table.sum(axis=1), table.sum(axis=0)) / table.to_numpy().sum()chi2_manual = ((table.to_numpy() - expected) ** 2 / expected).sum()res = stats.chi2_contingency(table, correction=False)print( f"manual chi2 = {chi2_manual:.2f}, scipy chi2 = {res.statistic:.2f}" f", df = {res.dof}")print(f"p = {res.pvalue:.2e}")rates = customers.groupby("has_autopay")["churned"].mean().round(3)print("churn rate by autopay:", rates.to_dict())churned 0 1has_autopay0 1840 5151 2197 448manual chi2 = 19.48, scipy chi2 = 19.48, df = 1p = 1.02e-05churn rate by autopay: {0: 0.219, 1: 0.169}The observed counts are far from the expected ones, and customers without autopay churn more often: 21.9% against 16.9%. For 2×2 tables, SciPy applies Yates’ continuity correction by default, which makes the test a little conservative. The code passes correction=False to match the textbook formula. With large counts, the two versions barely differ.
The test needs an expected count of at least about 5 in each cell. With smaller counts, use stats.fisher_exact (2×2) or merge rare categories. The chi-square test says whether two variables are related, not how strongly. Example 5 adds effect sizes for that.
ANOVA and the Kruskal–Wallis test
Section titled “ANOVA and the Kruskal–Wallis test”To compare the means of three or more groups, do not run a t-test for every pair: the false alarms add up (see Multiple testing). One-way ANOVA (analysis of variance) tests all groups at once. : all group means are equal. Its F statistic compares the spread between the group means with the spread within the groups:
is the number of groups. If the groups truly share one mean, is near 1. Do customers in the four regions differ in session length?
groups = [g.to_numpy() for _, g in customers.groupby("region")["avg_session_minutes"]]anova = stats.f_oneway(*groups)kw = stats.kruskal(*groups)by_region = customers.groupby("region")["avg_session_minutes"]print(by_region.mean().round(2).to_dict())
minutes = customers["avg_session_minutes"]k_groups, n_all = by_region.ngroups, len(minutes)between_ss = (by_region.size() * (by_region.mean() - minutes.mean()) ** 2).sum()between = between_ss / (k_groups - 1)within = ((minutes - by_region.transform("mean")) ** 2).sum() / (n_all - k_groups)print(f"manual F = {between / within:.3f}")print(f"ANOVA F = {anova.statistic:.3f}, p = {anova.pvalue:.3f}")print(f"Kruskal-Wallis H = {kw.statistic:.3f}, p = {kw.pvalue:.3f}"){'East': 14.16, 'North': 14.66, 'South': 14.46, 'West': 14.06}manual F = 1.499ANOVA F = 1.499, p = 0.213Kruskal-Wallis H = 4.214, p = 0.239The four means differ by less than a minute, and both tests find no evidence of a regional difference. *groups unpacks the list, so each region becomes its own argument (module 05).
ANOVA assumes independent observations, roughly normal groups (or large groups) and similar variances. When the data is strongly skewed, has outliers or is ordinal (ratings from 1 to 5), use the Kruskal–Wallis test. It ranks all values together and tests whether one group tends to have larger values than another. A significant ANOVA says only that some means differ. A post hoc test then finds which pairs differ while it controls the false alarms, for example Tukey’s HSD with stats.tukey_hsd(*groups).
The Mann–Whitney U test
Section titled “The Mann–Whitney U test”The Mann–Whitney U test (also called the Wilcoxon rank-sum test) is the nonparametric alternative to the two-sample t-test. It ranks all values of both groups together and checks whether one group’s ranks are systematically higher. counts, over all pairs of one value from each group, how often the first group’s value is larger (ties count one half). is then the probability that a random value of group 1 beats a random value of group 2. This is a simple effect size: 0.5 means no tendency either way.
Among buyers, revenue is log-normal and right-skewed. Did buyers spend more on the new page?
buyers_ab = ab[ab["converted"] == 1]rev_t = buyers_ab.loc[buyers_ab["group"] == "treatment", "revenue"]rev_c = buyers_ab.loc[buyers_ab["group"] == "control", "revenue"]mw = stats.mannwhitneyu(rev_t, rev_c, alternative="two-sided")print( f"median order value: treatment {rev_t.median():.2f}" f", control {rev_c.median():.2f}")print(f"U = {mw.statistic:,.0f}, p = {mw.pvalue:.3f}")prob_greater = mw.statistic / (len(rev_t) * len(rev_c))print(f"P(treatment order > control order) = {prob_greater:.3f}")median order value: treatment 33.97, control 35.66U = 141,931, p = 0.282P(treatment order > control order) = 0.481The probability is close to 0.5 and the p-value is large: there is no evidence that the new page changed the order value. That is not proof of “no change”. A confidence interval shows which changes the data rules out. Bootstrap the difference in medians; with two samples, bootstrap resamples each group separately:
def median_diff(x, y, axis=-1): return np.median(x, axis=axis) - np.median(y, axis=axis)
boot_diff = stats.bootstrap( (rev_t.to_numpy(), rev_c.to_numpy()), median_diff, n_resamples=5_000, rng=np.random.default_rng(42),)ci = boot_diff.confidence_intervalprint(f"difference in medians {rev_t.median() - rev_c.median():+.2f} USD," f" 95% CI {ci.low:+.2f} to {ci.high:+.2f} USD")difference in medians -1.69 USD, 95% CI -5.40 to +1.96 USDThe interval rules out a drop of more than about 5.40 USD and a rise of more than about 1.96 USD in the median order. Changes inside that range remain possible; with about 500 buyers per group, the test cannot see them. The axis argument lets bootstrap compute all resamples at once. Mann–Whitney is not strictly a test of medians; it tests whether one distribution tends to give larger values.
Effect size
Section titled “Effect size”A p-value says whether an effect is distinguishable from noise. An effect size says how large the effect is. Always report both. With 10 million users (5 million per group), a change from 10.0% to 10.1% conversion is highly significant and probably worthless:
from statsmodels.stats.proportion import proportions_ztest
n_big = 5_000_000buyers_big = [int(0.101 * n_big), int(0.100 * n_big)]z_big, p_big = proportions_ztest(buyers_big, [n_big, n_big])print(f"10.1% vs 10.0% with {n_big:,} per group: z = {z_big:.2f}, p = {p_big:.1e}")10.1% vs 10.0% with 5,000,000 per group: z = 5.26, p = 1.5e-07| Effect size | Formula | Use |
|---|---|---|
| Difference in means | in the original unit (USD, seconds) | |
| Cohen’s d | difference in pooled standard deviations, unit-free | |
| Difference in proportions | in percentage points | |
| Relative lift | in percent of the baseline | |
| Odds ratio | 2×2 tables, logistic regression | |
| Cramér’s V | strength of a chi-square association, 0 to 1 |
The pooled standard deviation combines both groups: . The odds of an event are : a 20% churn rate means odds of 0.25, “1 churner for every 4 stayers”.
def cohens_d(a: pd.Series, b: pd.Series) -> float: """Standardized mean difference with the pooled standard deviation.""" 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
p_t = converted[is_treatment].mean()p_c = converted[~is_treatment].mean()odds_ratio = (p_t / (1 - p_t)) / (p_c / (1 - p_c))print(f"time on page, Cohen's d: {cohens_d(treat_time, ctrl_time):.3f}")print(f"conversion: {p_t:.4f} vs {p_c:.4f}")print(f"difference: {100 * (p_t - p_c):.2f} percentage points")print(f"relative lift: {100 * (p_t - p_c) / p_c:.1f}%")print(f"odds ratio: {odds_ratio:.3f}")time on page, Cohen's d: 0.170conversion: 0.1166 vs 0.1012difference: 1.55 percentage pointsrelative lift: 15.3%odds ratio: 1.173Cohen’s rough benchmarks call = 0.2 small, 0.5 medium and 0.8 large. The time-on-page effect is small in standardized terms, even though its p-value is tiny. Benchmarks are a last resort: judge an effect in business units first. A 1.55-point gain on a 10% baseline is a 15% lift in sales from the checkout page, which is large for a business.
Power and sample size
Section titled “Power and sample size”The power of a test is the probability that it detects an effect of a given size, when that effect is real. Four quantities are linked; fix any three and the fourth follows:
| Lever | Effect on power |
|---|---|
| Effect size (larger) | more power |
| Sample size (larger) | more power |
| (larger, e.g. 0.10) | more power, more false alarms |
| Noise (smaller) | more power |
Before an experiment, choose the minimum detectable effect (MDE): the smallest effect that would be worth acting on. Then compute the sample size that detects it with 80% power (the usual target). statsmodels.stats.power solves for whichever quantity you leave out. For proportions, proportion_effectsize converts two rates to Cohen’s h, the effect size the power functions expect. It compares the rates on an arcsine scale, on which the noise of a proportion is the same at every level:
from statsmodels.stats.power import NormalIndPower, TTestIndPowerfrom statsmodels.stats.proportion import proportion_effectsize
h_manual = 2 * np.arcsin(np.sqrt(0.12)) - 2 * np.arcsin(np.sqrt(0.10))h_lib = proportion_effectsize(0.12, 0.10)print(f"Cohen's h by hand {h_manual:.4f} | statsmodels {h_lib:.4f}")prop_power = NormalIndPower()for target in (0.12, 0.115, 0.11): h = proportion_effectsize(target, 0.10) # Cohen's h for target vs 10% baseline n_needed = prop_power.solve_power(effect_size=h, alpha=0.05, power=0.80) print(f"10% -> {target:.1%}: h = {h:.4f}, n per group = {np.ceil(n_needed):,.0f}")
h_obs = proportion_effectsize(0.115, 0.10)print(f"power with 5,000 per group for 10% -> 11.5%: " f"{prop_power.power(effect_size=h_obs, nobs1=5_000, alpha=0.05):.3f}")n_d = TTestIndPower().solve_power(effect_size=0.2, alpha=0.05, power=0.80)print(f"t-test, d = 0.2: n per group = {np.ceil(n_d):.0f}")Cohen's h by hand 0.0640 | statsmodels 0.064010% -> 12.0%: h = 0.0640, n per group = 3,83510% -> 11.5%: h = 0.0485, n per group = 6,68710% -> 11.0%: h = 0.0326, n per group = 14,745power with 5,000 per group for 10% -> 11.5%: 0.678t-test, d = 0.2: n per group = 394Halving the effect roughly quadruples the sample size, because the standard error shrinks with . With 5,000 users per group, the checkout test had only about a 68% chance to detect a true 1.5-point lift. It found one, but a team that ran many such tests would miss about 1 in 3 real lifts of that size.
Multiple testing
Section titled “Multiple testing”Run one test at and the false-alarm risk is 5%. Run 20 independent tests on data with no real effects, and the chance of at least one false alarm is . This is the multiple testing problem. It appears whenever you test many metrics, many segments (“does it work on mobile? in Germany? on Tuesdays?”) or peek at a running test many times. Searching many tests and reporting only the significant ones is called p-hacking.
The family-wise error rate (FWER) is the probability of at least one false positive among all the tests. Two standard corrections:
- Bonferroni: test each of the hypotheses at (equivalently, multiply each p-value by ). It controls the FWER. It is simple and strict, so it costs power.
- Benjamini–Hochberg (BH): it controls the false discovery rate (FDR), the expected share of false positives among the results you call significant. Sort the p-values . Find the largest rank with , then reject the hypotheses with ranks 1 to . A p-value can miss its own threshold and still be rejected, because a larger p-value further down the list passed. It keeps more power and suits exploratory screens.
from statsmodels.stats.multitest import multipletests
m = np.arange(1, 21)print("FWER for 1, 5, 10, 20 tests:", (1 - 0.95 ** m[[0, 4, 9, 19]]).round(3))
p_metrics = np.array( [0.001, 0.008, 0.039, 0.041, 0.042, 0.060, 0.074, 0.205, 0.212, 0.216])for method in ("bonferroni", "fdr_bh"): reject, p_adj, _, _ = multipletests(p_metrics, alpha=0.05, method=method) print(f"{method:<10} significant: {reject.sum()} | adjusted: {p_adj[:5].round(3)}")
ranked = np.sort(p_metrics)thresholds = np.arange(1, len(ranked) + 1) / len(ranked) * 0.05passing = np.nonzero(ranked <= thresholds)[0]print("BH thresholds:", thresholds[:5].round(3))print("BH by hand: reject the", passing.max() + 1, "smallest p-values")FWER for 1, 5, 10, 20 tests: [0.05 0.226 0.401 0.642]bonferroni significant: 1 | adjusted: [0.01 0.08 0.39 0.41 0.42]fdr_bh significant: 2 | adjusted: [0.01 0.04 0.084 0.084 0.084]BH thresholds: [0.005 0.01 0.015 0.02 0.025]BH by hand: reject the 2 smallest p-valuesTen metrics of a test give five raw p-values below 0.05. Bonferroni keeps one; BH keeps two. The other three were borderline and are not trustworthy as a group. scipy.stats.false_discovery_control(p_metrics) returns the same BH-adjusted p-values. Decide the primary metric before the test starts; treat the rest as exploratory.
Correlation and causation
Section titled “Correlation and causation”Module 27 measured correlation: how strongly two numeric variables move together. stats.pearsonr adds a p-value and a confidence interval to the coefficient, and stats.spearmanr gives the rank-based version for monotonic, non-linear relationships.
A correlation, however strong, does not show that one variable causes the other. A confounder is a third variable that drives both. A shop sells fans and ice cream. Hot days raise both sales, and neither product causes the other. Simulate 200 days in which fan sales have no effect on ice cream sales:
rng = np.random.default_rng(42)temp = rng.normal(24, 5, size=200) # daily temperature: the confounderfans = 2.0 * temp + rng.normal(0, 6, size=200) # driven by temperature onlyice_cream = 5.0 * temp + rng.normal(0, 15, size=200) # also driven by temperature onlyshop = pd.DataFrame({"temp": temp, "fans": fans, "ice_cream": ice_cream})
r = stats.pearsonr(shop["fans"], shop["ice_cream"])print(f"Pearson r = {r.statistic:.3f}, p = {r.pvalue:.1e}")naive = smf.ols("ice_cream ~ fans", data=shop).fit()adjusted = smf.ols("ice_cream ~ fans + temp", data=shop).fit()print(f"naive slope of fans: {naive.params['fans']:.3f} " f"(p = {naive.pvalues['fans']:.1e})")print(f"adjusted slope of fans: {adjusted.params['fans']:.3f} " f"(p = {adjusted.pvalues['fans']:.3f})")Pearson r = 0.669, p = 2.7e-27naive slope of fans: 1.690 (p = 2.7e-27)adjusted slope of fans: 0.077 (p = 0.665)Fan and ice-cream sales correlate strongly, and a naive regression says “each extra fan sells about 1.7 ice creams”. Once the model includes temperature, the fan effect shrinks to about zero and is no longer significant. Holding the temperature fixed, fans tell you nothing about ice cream. (The smf.ols formula API is explained in the next section.)
flowchart TD
T["Temperature<br/>(confounder)"] --> F["Fan sales"]
T --> I["Ice-cream sales"]
F -. "correlation,<br/>no causation" .- I
How to get closer to causation:
- Randomize. A randomized controlled experiment assigns the treatment by chance, such as a coin flip for each user. Chance cannot depend on temperature, income or anything else, so randomization breaks every confounder, even the unknown ones. This is why A/B tests can show causation.
- Adjust. Without an experiment, include known confounders in a regression, as above. You can only adjust for confounders that you measured, so the conclusion stays weaker.
- Think about the direction. Customers with many support tickets churn more. Do tickets cause churn, or do unhappy customers both file tickets and leave?
A spurious correlation is one with no causal link at all, often between two series that both trend over time (shop revenue and the number of streaming subscribers both grew in 2023–2024).
Linear regression with statsmodels
Section titled “Linear regression with statsmodels”Module 18 fitted a line with least squares. Ordinary least squares (OLS) regression generalizes it to many predictors: . Each coefficient is the expected change in for a one-unit change in , holding the other predictors fixed. is the intercept. The error term is the part of that the predictors do not explain; it is never observed. A residual is its estimate: the gap between an observed value and the model’s prediction. OLS picks the coefficients that minimize the sum of squared residuals, .
The standard errors, p-values and CIs of OLS rely on four assumptions:
- Linearity: the expected value of is a linear function of the predictors (after any transforms such as
np.log). - Independent errors: one observation’s error says nothing about another’s.
- Constant variance (homoscedasticity): the errors have the same spread for all fitted values. A spread that changes is heteroscedasticity.
- Roughly normal errors: needed only for small samples; with thousands of rows, the CLT covers the coefficients.
Check 1 and 3 with a plot of the residuals against the fitted values: it should show a shapeless band around 0. When the spread changes, keep the coefficients but use heteroscedasticity-robust standard errors: .fit(cov_type="HC3"). Example 7 does both.
scikit-learn (module 35) fits the same model for prediction. statsmodels adds inference: a standard error, a t-test, a p-value and a confidence interval for every coefficient. Its formula API (statsmodels.formula.api, imported as smf) describes the model as a string, in the style of R:
| Formula | Means |
|---|---|
"price ~ sqft" |
price explained by sqft, with an intercept |
"price ~ sqft + bedrooms" |
two predictors |
"price ~ C(neighborhood)" |
treat as categorical: one dummy variable (0/1 column) per level except a reference level |
"np.log(price) ~ np.log(sqft)" |
apply a function inside the formula |
"price ~ sqft * has_pool" |
both main effects and their interaction (sqft:has_pool) |
"price ~ I(sqft / 1000)" |
I() protects arithmetic, so / divides |
"price ~ sqft - 1" |
no intercept |
The fitted result has these attributes:
| Attribute | Gives |
|---|---|
params |
the coefficients |
bse |
their standard errors |
tvalues, pvalues |
t statistic and p-value for : coefficient = 0 |
conf_int(alpha=0.05) |
a 95% CI per coefficient |
rsquared, rsquared_adj |
and adjusted |
nobs |
number of rows used (rows with missing values are dropped) |
resid, fittedvalues |
residuals and predictions on the training data |
predict(new_df) |
predictions for new rows |
Adjusted is with a penalty for each extra predictor. It rises only if a new predictor helps more than chance would.
Worked examples
Section titled “Worked examples”Example 1 — Describe house prices
Section titled “Example 1 — Describe house prices”Goal: A real-estate team asks for “the typical house price” per neighborhood. Describe the center, spread and shape of price in data/houses.csv, and decide which numbers to report.
Step 1 — Summarize the whole column
Section titled “Step 1 — Summarize the whole column”print(houses["price"].describe().map("{:,.0f}".format))print(f"mean / median = {price.mean() / price.median():.2f}")count 3,000mean 476,466std 318,751min 117,50025% 278,50050% 376,00075% 560,375max 3,730,500Name: price, dtype: strmean / median = 1.27describe() gives the count, mean, standard deviation, minimum, quartiles and maximum. The mean is 27% above the median, and the maximum is ten times the median: a sure sign of a long right tail.
Step 2 — Compare neighborhoods with robust statistics
Section titled “Step 2 — Compare neighborhoods with robust statistics”def iqr(s: pd.Series) -> float: return s.quantile(0.75) - s.quantile(0.25)
summary = ( houses.groupby("neighborhood")["price"] .agg(n="count", mean="mean", median="median", sd="std", iqr=iqr) .sort_values("median"))money = ["mean", "median", "sd", "iqr"]summary[money] = summary[money].round(-3).astype(int)print(summary) n mean median sd iqrneighborhoodCedar Park 407 262000 249000 75000 76000Westfield 450 274000 267000 74000 101000Old Town 276 358000 335000 109000 128000Downtown 356 352000 342000 89000 115000Maple Grove 454 440000 403000 185000 183000Riverside 370 516000 477000 197000 241000Oak Hill 380 811000 724000 376000 447000Lakeview 307 901000 777000 462000 466000.round(-3) rounds to the nearest thousand. In every neighborhood, the mean is above the median, so the skew is not caused by mixing cheap and expensive areas: it exists inside each area. Lakeview and Oak Hill have both the highest prices and the widest spread, because a few very large houses there pull the means up. Report the medians as the “typical price” and the IQR as the spread.
Step 3 — Measure and plot the skew
Section titled “Step 3 — Measure and plot the skew”print(f"skew: price {price.skew():.2f}, log price {np.log(price).skew():.2f}")fig, axes = plt.subplots(1, 2, figsize=(10, 4))axes[0].hist(price / 1000, bins=60, color="#4c78a8")axes[0].axvline(price.mean() / 1000, color="#c0392b", linestyle="--", label="mean")axes[0].axvline(price.median() / 1000, color="#2e7d32", label="median")axes[0].set(title="Price", xlabel="price (thousand USD)", ylabel="houses")axes[0].legend()axes[1].hist(np.log(price), bins=60, color="#4c78a8")axes[1].set(title="Log price", xlabel="log(price)")fig.tight_layout()plt.show()skew: price 2.67, log price 0.70
The left panel shows why the mean and the median disagree: the tail on the right pulls the mean away from the bulk of the data. On the log scale, the distribution is close to a bell curve, with a mild right tail (skew 0.70). That suits the regression in Example 7.
Common mistakes:
- Reporting only the mean of a skewed variable. Report the median and the IQR, and add the mean when totals matter.
- Comparing standard deviations of groups with very different levels. A spread of 75,000 USD is large in Cedar Park and small in Lakeview. Compare on the log scale or with the IQR relative to the median.
- Using
np.std(x)on a sample andSeries.std()elsewhere in the same report. They use differentddof; passddof=1explicitly in NumPy.
Example 2 — Watch the central limit theorem on order revenue
Section titled “Example 2 — Watch the central limit theorem on order revenue”Goal: Order-line revenue in data/sales.csv is extremely skewed. Show that the average revenue of a random sample of lines still follows a normal curve, and find how large the sample must be.
Step 1 — Look at the population
Section titled “Step 1 — Look at the population”revenue = sales["revenue"].to_numpy()mu, sigma = revenue.mean(), revenue.std()print( f"lines {len(revenue):,} | mean {mu:.2f} | sd {sigma:.2f}" f" | median {np.median(revenue):.2f}")print(f"skew {stats.skew(revenue):.2f}")lines 20,228 | mean 177.80 | sd 314.83 | median 79.99skew 5.08The standard deviation is almost twice the mean and the skew is about 5: half the lines are under 80 USD, and a long tail of electronics lines reaches over 1,000 USD. No one would call this data normal. Here the 20,228 lines play the role of the population.
Step 2 — Draw many samples and keep their means
Section titled “Step 2 — Draw many samples and keep their means”rng = np.random.default_rng(42)samples, sample_means = {}, {}for n in (5, 30, 200): samples[n] = rng.choice(revenue, size=(4_000, n)) # 4,000 samples of n lines sample_means[n] = samples[n].mean(axis=1) m = sample_means[n] print(f"n={n:<3} mean of means {m.mean():6.2f} | sd {m.std():6.2f}" f" | sigma/sqrt(n) {sigma / np.sqrt(n):6.2f} | skew {stats.skew(m):.2f}")n=5 mean of means 175.15 | sd 136.50 | sigma/sqrt(n) 140.80 | skew 2.26n=30 mean of means 177.48 | sd 57.23 | sigma/sqrt(n) 57.48 | skew 0.87n=200 mean of means 177.81 | sd 21.99 | sigma/sqrt(n) 22.26 | skew 0.29rng.choice(revenue, size=(4_000, n)) draws 4,000 samples of n lines at once, with replacement. .mean(axis=1) averages each row. The mean of the sample means always lands near the true mean. Their spread follows . And the skew of the means drops toward 0 as grows: the shape becomes normal.
Step 3 — Plot the sampling distributions
Section titled “Step 3 — Plot the sampling distributions”fig, axes = plt.subplots(1, 4, figsize=(14, 3.5))axes[0].hist(revenue, bins=80, color="#9aa5b1")axes[0].set(title="Population: line revenue", xlabel="USD", xlim=(0, 1500))for ax, n in zip(axes[1:], (5, 30, 200), strict=True): m = sample_means[n] ax.hist(m, bins=50, density=True, color="#4c78a8", alpha=0.8) grid = np.linspace(m.min(), m.max(), 200) ax.plot(grid, stats.norm.pdf(grid, mu, sigma / np.sqrt(n)), color="#c0392b") ax.set(title=f"Means of n = {n}", xlabel="sample mean (USD)")fig.tight_layout()plt.show()
The red curve is the normal distribution with mean and standard deviation , drawn without fitting anything to the simulated means. For it fits badly. For the right tail is still a little too long. For the fit is close. For data this skewed, “n ≥ 30” is not enough.
Step 4 — Check the 95% rule
Section titled “Step 4 — Check the 95% rule”for n in (5, 30, 200): se = sigma / np.sqrt(n) low_tail = (sample_means[n] < mu - 1.96 * se).mean() high_tail = (sample_means[n] > mu + 1.96 * se).mean() print( f"n={n:<3} below mu - 1.96 SE: {low_tail:.3f}" f" | above mu + 1.96 SE: {high_tail:.3f}" )n=5 below mu - 1.96 SE: 0.000 | above mu + 1.96 SE: 0.046n=30 below mu - 1.96 SE: 0.000 | above mu + 1.96 SE: 0.046n=200 below mu - 1.96 SE: 0.014 | above mu + 1.96 SE: 0.029If the means were exactly normal, 2.5% would fall below and 2.5% above . For and , about 4.6% of the means fall above and none below. A sample mean that high gives an interval “mean ± 1.96 SE” that lies entirely above . So, with the true , the misses are all on one side, but the total miss rate stays near 5%. With , the tails hold 1.4% and 2.9%: closer to even.
Step 5 — Build real t-intervals with each sample’s own sd
Section titled “Step 5 — Build real t-intervals with each sample’s own sd”for n in (5, 30, 200): s_n = samples[n].std(axis=1, ddof=1) # each sample's own sd half = stats.t.ppf(0.975, df=n - 1) * s_n / np.sqrt(n) low, high = sample_means[n] - half, sample_means[n] + half print(f"n={n:<3} coverage {((low <= mu) & (mu <= high)).mean():.3f}" f" | entirely below mu {(high < mu).mean():.3f}" f" | entirely above mu {(low > mu).mean():.3f}")r = np.corrcoef(sample_means[30], samples[30].std(axis=1, ddof=1))[0, 1]print(f"n=30: correlation between sample mean and sample sd: {r:.2f}")n=5 coverage 0.739 | entirely below mu 0.261 | entirely above mu 0.000n=30 coverage 0.827 | entirely below mu 0.171 | entirely above mu 0.002n=200 coverage 0.927 | entirely below mu 0.067 | entirely above mu 0.006n=30: correlation between sample mean and sample sd: 0.89Real intervals do not know ; they use each sample’s . That changes the picture. A sample that misses the rare expensive lines has a low mean and a small (the two correlate at about 0.89), so its interval is too narrow and lies entirely below . The coverage of the nominal 95% t-interval is only about 74% at , 83% at and 93% at , and almost every miss is below . For skewed money data, even 200 rows are not quite enough. Use more data, analyze the log, or use a BCa bootstrap interval, and check the method with a simulation like this one.
Common mistakes:
- Believing that the CLT makes the data normal. It is about the distribution of the mean over repeated samples.
- Treating “n ≥ 30” as a universal rule. Heavy right tails need much more: here the t-interval covers only 83% at n = 30. Check with a simulation like this one or use the bootstrap.
- Forgetting independence. Order lines of the same order or the same customer are related; the CLT needs independent draws.
Example 3 — Estimate charges and churn from a customer survey
Section titled “Example 3 — Estimate charges and churn from a customer survey”Goal: The finance team can survey only 200 random customers. Estimate the mean and median monthly charge and the churn rate, with 95% confidence intervals. Then check, with the full file, how often such intervals are right.
Step 1 — Draw the survey sample
Section titled “Step 1 — Draw the survey sample”sample = customers.sample(n=200, random_state=42)x = sample["monthly_charges"]n = len(x)print( f"n = {n}, mean {x.mean():.2f}, sd {x.std():.2f}" f", churned {sample['churned'].sum()}")true_churn = customers["churned"].mean()print(f"true values: mean {charges.mean():.2f}, churn {true_churn:.4f}")n = 200, mean 63.58, sd 22.85, churned 39true values: mean 60.84, churn 0.1926sample(n=200, random_state=42) draws 200 rows without replacement, the same 200 on every run. The second line shows the population values that the survey tries to estimate. Real life never shows you that line.
Step 2 — Build a t-interval for the mean
Section titled “Step 2 — Build a t-interval for the mean”se = x.std(ddof=1) / np.sqrt(n)t_crit = stats.t.ppf(0.975, df=n - 1)low, high = x.mean() - t_crit * se, x.mean() + t_crit * seprint(f"SE {se:.3f}, t critical {t_crit:.4f}, margin of error {t_crit * se:.2f}")print(f"manual 95% CI: {low:.2f} to {high:.2f}")scipy_ci = stats.t.interval(0.95, df=n - 1, loc=x.mean(), scale=se)print(f"scipy 95% CI: {scipy_ci[0]:.2f} to {scipy_ci[1]:.2f}")SE 1.616, t critical 1.9720, margin of error 3.19manual 95% CI: 60.40 to 66.77scipy 95% CI: 60.40 to 66.77The interval is “sample mean ± about 2 standard errors”. It contains the true mean of 60.84 USD. stats.t.interval does the same arithmetic in one call, and stats.ttest_1samp(x, 0).confidence_interval() is a third way.
Step 3 — Build Wald and Wilson intervals for the churn rate
Section titled “Step 3 — Build Wald and Wilson intervals for the churn rate”from statsmodels.stats.proportion import proportion_confint
k = int(sample["churned"].sum())p_hat = k / nwald_margin = 1.96 * np.sqrt(p_hat * (1 - p_hat) / n)print(f"p_hat = {p_hat:.3f}")print(f"Wald manual: {p_hat - wald_margin:.4f} to {p_hat + wald_margin:.4f}")for method in ("normal", "wilson"): lo, hi = proportion_confint(k, n, alpha=0.05, method=method) print(f"{method:<6} {lo:.4f} to {hi:.4f}")p_hat = 0.195Wald manual: 0.1401 to 0.2499normal 0.1401 to 0.2499wilson 0.1461 to 0.2554statsmodels calls the Wald interval "normal". The Wilson interval is not centered on : it leans toward 0.5, which corrects the Wald interval’s habit of being too narrow. Both contain the true churn rate of 19.26%. With 200 customers, the churn rate is known only to about ±5.5 percentage points.
Step 4 — Bootstrap the median
Section titled “Step 4 — Bootstrap the median”rng = np.random.default_rng(42)boot = stats.bootstrap((x.to_numpy(),), np.median, n_resamples=5_000, rng=rng)ci = boot.confidence_intervalprint(f"sample median {x.median():.2f}")print(f"BCa bootstrap 95% CI: {ci.low:.2f} to {ci.high:.2f}")print(f"bootstrap SE: {boot.standard_error:.3f}")print(f"true median: {np.median(charges):.2f}")sample median 59.72BCa bootstrap 95% CI: 58.15 to 62.42bootstrap SE: 1.115true median: 58.86The median has no simple standard-error formula, so the bootstrap estimates its uncertainty by resampling. The data goes in as a tuple, (x,), because bootstrap also handles statistics of several samples. Its default method, BCa (bias-corrected and accelerated), adjusts the percentile interval for bias and skew. rng makes the resampling repeatable.
Step 5 — Check the coverage by simulation
Section titled “Step 5 — Check the coverage by simulation”rng = np.random.default_rng(42)surveys = rng.choice(charges, size=(2_000, n), replace=True) # 2,000 surveys of 200means = surveys.mean(axis=1)ses = surveys.std(axis=1, ddof=1) / np.sqrt(n)covered = np.abs(means - charges.mean()) <= t_crit * sesprint(f"share of 95% t-intervals that contain the true mean: {covered.mean():.3f}")share of 95% t-intervals that contain the true mean: 0.952About 95% of the 2,000 intervals contain the true mean. This is the precise meaning of “95% confidence”: a statement about the method over many repetitions, not about one interval.
Common mistakes:
- Saying “there is a 95% probability that the true mean is in 60.4–66.8”. The true mean is fixed. Say “we are 95% confident”, meaning the method captures the truth 95% of the time.
- Using the Wald interval for small samples or rare events. With 3 churners out of 40, it can go below 0. Use Wilson.
- Using
ddof=0for the standard error, or the normal critical value 1.96 for a small sample. Useddof=1and the t distribution.
Example 4 — Compare churners and stayers
Section titled “Example 4 — Compare churners and stayers”Goal: The retention team wants to know how churners differ from customers who stay. Test the difference in monthly charges and support tickets, and say how large each difference is.
Step 1 — Summarize by group
Section titled “Step 1 — Summarize by group”churned = customers["churned"] == 1cols = ["monthly_charges", "tenure_months", "support_tickets", "logins_last_30d"]print(customers.groupby("churned")[cols].agg(["mean", "median"]).round(2)) monthly_charges tenure_months support_tickets logins_last_30d mean median mean median mean median mean medianchurned0 59.47 58.27 25.79 20.0 1.12 1.0 12.11 10.01 66.58 61.79 11.72 6.0 1.74 1.0 10.20 9.0Churners pay more, are newer, file more tickets and log in less. The question is which differences are larger than chance, and which are large enough to matter.
Step 2 — Run a Welch t-test on monthly charges
Section titled “Step 2 — Run a Welch t-test on monthly charges”a = customers.loc[churned, "monthly_charges"]b = customers.loc[~churned, "monthly_charges"]res = stats.ttest_ind(a, b, equal_var=False)ci = res.confidence_interval()print( f"churners {a.mean():.2f} USD vs stayers {b.mean():.2f} USD" f" (n = {len(a)} vs {len(b)})")print(f"Welch t = {res.statistic:.2f}, df = {res.df:.0f}, p = {res.pvalue:.1e}")print(f"95% CI for the difference: {ci.low:.2f} to {ci.high:.2f} USD")churners 66.58 USD vs stayers 59.47 USD (n = 963 vs 4037)Welch t = 7.93, df = 1319, p = 4.7e-1595% CI for the difference: 5.35 to 8.87 USDChurners pay about 7 USD more per month, with a CI of about 5.4 to 8.9 USD. The groups have different sizes and variances, which is exactly the case Welch’s test handles. The p-value is tiny: a difference this large almost never happens by chance with these sample sizes.
Step 3 — Measure the effect sizes
Section titled “Step 3 — Measure the effect sizes”for col in cols: d = cohens_d(customers.loc[churned, col], customers.loc[~churned, col]) print(f"{col:<16} d = {d:+.2f}")monthly_charges d = +0.31tenure_months d = -0.74support_tickets d = +0.54logins_last_30d d = -0.24Tenure has the largest standardized effect: churners are much newer customers. Support tickets follow with a medium effect. The charges and logins effects are small, even though they are highly significant. With 5,000 customers, even small differences are detectable. The sign shows the direction: negative means churners have less.
Step 4 — Use Mann–Whitney U for the support tickets
Section titled “Step 4 — Use Mann–Whitney U for the support tickets”t_churn = customers.loc[churned, "support_tickets"]t_stay = customers.loc[~churned, "support_tickets"]mw = stats.mannwhitneyu(t_churn, t_stay, alternative="two-sided")prob = mw.statistic / (len(t_churn) * len(t_stay))print(f"U = {mw.statistic:,.0f}, p = {mw.pvalue:.1e}")print(f"P(churner has more tickets than a stayer) = {prob:.3f}")print(customers.groupby("churned")["support_tickets"].value_counts(normalize=True) .unstack().round(3).iloc[:, :6])U = 2,429,174, p = 2.8e-36P(churner has more tickets than a stayer) = 0.625support_tickets 0 1 2 3 4 5churned0 0.330 0.362 0.202 0.076 0.024 0.0041 0.211 0.290 0.221 0.155 0.090 0.020Support tickets are small whole numbers with many ties at 0 and 1. A rank test suits such data better than a t-test. The probability is above 0.5: a random churner tends to have more tickets than a random stayer (ties count as one half). The table shows the shift: about a third of stayers never filed a ticket, against about a fifth of churners.
Common mistakes:
- Concluding that high charges cause churn. This is observational data. Premium customers pay more and may differ in many other ways. Only an experiment, such as a randomized discount, shows the causal effect.
- Running Student’s t-test (
equal_var=True, the SciPy default) on groups of very different size and spread. - Reporting “p below 0.001” without the size of the difference. Add the difference in units, its CI and an effect size.
Example 5 — Test whether contract type and churn are related
Section titled “Example 5 — Test whether contract type and churn are related”Goal: Customers can pay month-to-month or sign a one-year or two-year contract. Test whether churn depends on the contract type, and measure how strong the relationship is.
Step 1 — Build the contingency table
Section titled “Step 1 — Build the contingency table”ct = pd.crosstab(customers["contract"], customers["churned"])print(ct)print(customers.groupby("contract")["churned"].mean().round(3))churned 0 1contractmonth-to-month 1961 823one-year 1117 108two-year 959 32contractmonth-to-month 0.296one-year 0.088two-year 0.032Name: churned, dtype: float64Each cell counts customers: for example, 823 month-to-month customers churned. The churn rate falls from almost 30% to about 3% as the contract gets longer.
Step 2 — Run the chi-square test
Section titled “Step 2 — Run the chi-square test”chi = stats.chi2_contingency(ct)print(f"chi2 = {chi.statistic:.1f}, df = {chi.dof}, p = {chi.pvalue:.1e}")print("expected counts under independence:")print(pd.DataFrame(chi.expected_freq, index=ct.index, columns=ct.columns).round(1))print("smallest expected count:", chi.expected_freq.min().round(1))chi2 = 439.7, df = 2, p = 3.3e-96expected counts under independence:churned 0 1contractmonth-to-month 2247.8 536.2one-year 989.1 235.9two-year 800.1 190.9smallest expected count: 190.9With a 3×2 table, df = (3 − 1)(2 − 1) = 2. Under independence, 536 month-to-month customers would churn; 823 did. The smallest expected count is far above 5, so the chi-square approximation is valid. The p-value is astronomically small: contract type and churn are clearly related. Yates’ correction applies only to 2×2 tables, so it does not change this result.
Step 3 — Measure the strength with Cramér’s V
Section titled “Step 3 — Measure the strength with Cramér’s V”v = stats.contingency.association(ct, method="cramer")n_rows, (r_levels, c_levels) = ct.to_numpy().sum(), ct.shapev_manual = np.sqrt(chi.statistic / (n_rows * (min(r_levels, c_levels) - 1)))print(f"Cramer's V = {v:.3f} | by hand {v_manual:.3f}")Cramer's V = 0.297 | by hand 0.297Cramér’s V rescales to the range 0 (no association) to 1 (perfect association). A value around 0.3 is a moderate association for survey-style data. Unlike and the p-value, V does not grow just because the sample grows.
Step 4 — Compute an odds ratio with a confidence interval
Section titled “Step 4 — Compute an odds ratio with a confidence interval”is_monthly = customers["contract"] == "month-to-month"labels = np.where(is_monthly, "monthly", "longer")contract_type = pd.Series(labels, name="contract_type")t2 = pd.crosstab(contract_type, customers["churned"]).loc[["monthly", "longer"], [1, 0]]print(t2)orr = stats.contingency.odds_ratio(t2.to_numpy())ci = orr.confidence_interval(confidence_level=0.95)print(f"odds ratio = {orr.statistic:.2f}, 95% CI {ci.low:.2f} to {ci.high:.2f}")churned 1 0contract_typemonthly 823 1961longer 140 2076odds ratio = 6.22, 95% CI 5.14 to 7.58odds_ratio expects the table as [[exposed & event, exposed & no event], [unexposed & event, unexposed & no event]], so the code reorders the rows and columns with .loc. The odds of churning are about 6 times higher for month-to-month customers than for customers with any longer contract. SciPy’s default is the conditional maximum-likelihood estimate, which is almost identical to the simple ratio of odds for large tables.
Common mistakes:
- Passing raw data instead of counts to
chi2_contingency. It needs the contingency table. - Reading a large as a strong association. With 50,000 customers, a weak association gives a huge . Report Cramér’s V or an odds ratio.
- Confusing an odds ratio of 6 with “6 times the churn rate”. The churn rate ratio here is 29.6% / 6.3% ≈ 4.7. Odds ratios and rate ratios are close only for rare events.
Example 6 — Analyze the checkout A/B test from start to finish
Section titled “Example 6 — Analyze the checkout A/B test from start to finish”Goal: An A/B test is a randomized experiment that compares two versions of something: here, the old checkout page (control) and a new one (treatment). data/ab_test.csv holds 10,000 users. Decide whether to launch the new page.
Step 1 — Plan the sample size before the test
Section titled “Step 1 — Plan the sample size before the test”baseline, mde = 0.10, 0.02 # the team cares about +2 points or moreh = proportion_effectsize(baseline + mde, baseline)n_plan = NormalIndPower().solve_power(effect_size=h, alpha=0.05, power=0.80)print(f"users needed per group: {np.ceil(n_plan):,.0f}")print(ab["group"].value_counts())users needed per group: 3,835groupcontrol 5002treatment 4998Name: count, dtype: int64Before the test, the team chose an MDE of 2 percentage points: a smaller gain would not pay for the work. At 80% power, that needs about 3,800 users per group. The test collected about 5,000 per group, so it is large enough for its plan.
Step 2 — Check the split for a sample ratio mismatch
Section titled “Step 2 — Check the split for a sample ratio mismatch”counts = ab["group"].value_counts().to_numpy()srm = stats.chisquare(counts) # H0: a 50/50 splitprint(f"chi2 = {srm.statistic:.4f}, p = {srm.pvalue:.3f}")chi2 = 0.0016, p = 0.968A sample ratio mismatch (SRM) is a split that differs from the planned ratio by more than chance allows. It signals a bug in the assignment or the logging, and it invalidates the test. The chi-square goodness-of-fit test compares observed counts with expected ones; chisquare assumes equal expected counts by default. 5,002 against 4,998 is perfectly normal.
Step 3 — Summarize the conversion per group
Section titled “Step 3 — Summarize the conversion per group”summary_ab = ab.groupby("group")["converted"].agg( buyers="sum", users="count", rate="mean")print(summary_ab)k_t, n_t = summary_ab.loc["treatment", ["buyers", "users"]]k_c, n_c = summary_ab.loc["control", ["buyers", "users"]] buyers users rategroupcontrol 506 5002 0.101treatment 583 4998 0.117The conversion rate is buyers divided by users (module 09). The rest of the analysis needs only these four counts.
Step 4 — Run the two-proportion z-test
Section titled “Step 4 — Run the two-proportion z-test”from statsmodels.stats.proportion import proportions_ztest
p_t, p_c = k_t / n_t, k_c / n_cp_pool = (k_t + k_c) / (n_t + n_c) # under H0 both groups share one ratez_manual = (p_t - p_c) / np.sqrt(p_pool * (1 - p_pool) * (1 / n_t + 1 / n_c))z, p_value = proportions_ztest([k_t, k_c], [n_t, n_c])print(f"manual z = {z_manual:.3f}")print(f"statsmodels z = {z:.3f}, two-sided p = {p_value:.4f}")manual z = 2.486statsmodels z = 2.486, two-sided p = 0.0129The test pools the two groups to estimate the shared rate under . , so you reject : the conversion rates differ. The permutation test in the concepts section gave almost the same p-value (0.013) without any formula.
Step 5 — Estimate the lift with confidence intervals
Section titled “Step 5 — Estimate the lift with confidence intervals”from statsmodels.stats.proportion import confint_proportions_2indep
diff = p_t - p_cse_diff = np.sqrt(p_t * (1 - p_t) / n_t + p_c * (1 - p_c) / n_c) # unpooled for the CIprint(f"difference {100 * diff:.2f} pp, Wald 95% CI " f"{100 * (diff - 1.96 * se_diff):.2f} to {100 * (diff + 1.96 * se_diff):.2f} pp")lo, hi = confint_proportions_2indep( k_t, n_t, k_c, n_c, compare="diff", method="newcomb")print(f"Newcombe 95% CI: {100 * lo:.2f} to {100 * hi:.2f} pp")lo_r, hi_r = confint_proportions_2indep(k_t, n_t, k_c, n_c, compare="ratio")print(f"relative lift {100 * (p_t / p_c - 1):.1f}%, 95% CI " f"{100 * (lo_r - 1):.1f}% to {100 * (hi_r - 1):.1f}%")difference 1.55 pp, Wald 95% CI 0.33 to 2.77 ppNewcombe 95% CI: 0.33 to 2.77 pprelative lift 15.3%, 95% CI 3.0% to 29.0%The interval uses the unpooled standard error, because it estimates the difference instead of assuming it is 0. With samples this large, the Wald and Newcombe intervals agree to two decimals. The new page adds about 1.5 percentage points of conversion, a relative lift of about 15%. The data is consistent with anything from about +0.3 to +2.8 points. The Newcombe interval is a Wilson-based interval for a difference of proportions; it is a little more accurate than Wald.
Step 6 — Judge the practical significance
Section titled “Step 6 — Judge the practical significance”break_even = 0.005 # +0.5 pp pays for the new pageprint(f"CI excludes 0 (statistically significant): {lo > 0}")print(f"whole CI above the break-even: {lo > break_even}")print(f"worst plausible case: {100 * (lo - break_even):+.2f} pp vs break-even")half_width = (hi - lo) / 2n_more = n_t * (half_width / (diff - break_even)) ** 2 # SE shrinks with sqrt(n)print(f"users per group for the CI to clear break-even: {n_more:,.0f}")CI excludes 0 (statistically significant): Truewhole CI above the break-even: Falseworst plausible case: -0.17 pp vs break-evenusers per group for the CI to clear break-even: 6,784Practical significance asks whether the effect is large enough to matter, not just whether it differs from 0. The new page has a running cost: the finance team says it pays for itself above +0.5 points. The lift is significant, but its CI reaches below the break-even point. In the worst plausible case, the page converts 0.17 points short of break-even. The MDE of Step 1 was a planning quantity; it does not enter this decision.
| CI for the lift | Decision |
|---|---|
| entirely above the break-even point | launch |
| above 0, but reaches below the break-even point | extend the test for precision (or launch, if the worst-case shortfall is acceptable) |
| includes 0 | no evidence of a gain; keep the old page or test a bolder change |
| entirely below 0 | the new page hurts; do not launch |
The last line of the output sizes the extension, assuming the true lift is near the observed 1.55 points: about 6,800 users per group make the whole CI clear the break-even. The team extends the test to that size instead of launching on an uncertain gain. Strictly, the final analysis is then a second look at the data, so it carries a little extra false-positive risk. One planned extension, sized in advance, keeps that risk small; repeated unplanned extensions are peeking.
Step 7 — Check a guardrail metric
Section titled “Step 7 — Check a guardrail metric”rpu_t = ab.loc[ab["group"] == "treatment", "revenue"]rpu_c = ab.loc[ab["group"] == "control", "revenue"]g = stats.ttest_ind(rpu_t, rpu_c, equal_var=False)g_ci = g.confidence_interval()print(f"revenue per user: {rpu_t.mean():.2f} vs {rpu_c.mean():.2f} USD")print(f"Welch p = {g.pvalue:.3f}, 95% CI {g_ci.low:.2f} to {g_ci.high:.2f} USD")revenue per user: 4.85 vs 4.38 USDWelch p = 0.157, 95% CI -0.18 to 1.11 USDA guardrail metric is a metric that must not get worse, even if the main metric improves: revenue, refunds, page load time. Revenue per user is higher in treatment, but the CI includes 0: revenue per user has a large variance, because most users spend 0 and a few spend a lot. The CI excludes any large loss, so the guardrail holds. For the order value of buyers, the concepts section found no evidence of a change, and its bootstrap CI ruled out a drop of more than about 5.40 USD in the median order.
Step 8 — Look at segments without fooling yourself
Section titled “Step 8 — Look at segments without fooling yourself”rows = []for device, part in ab.groupby("device"): k = part.groupby("group")["converted"].sum() nn = part.groupby("group")["converted"].count() _, p_seg = proportions_ztest( [k["treatment"], k["control"]], [nn["treatment"], nn["control"]] ) rows.append({"device": device, "control": k["control"] / nn["control"], "treatment": k["treatment"] / nn["treatment"], "p": p_seg})seg = pd.DataFrame(rows)seg["p_bh"] = multipletests(seg["p"], method="fdr_bh")[1]print(seg.round(4)) device control treatment p p_bh0 desktop 0.120 0.145 0.034 0.0901 mobile 0.085 0.100 0.060 0.0902 tablet 0.125 0.114 0.579 0.579Tablet users seem to convert worse on the new page. But the tablet group has only about 500 users per arm, and its p-value is large. Desktop has the smallest p-value but, after the BH correction for three segment tests, no single segment is significant on its own. Segment results are hypotheses for the next test, not conclusions. The overall result stays the primary one.
Common mistakes:
- Peeking: checking the p-value every day and stopping at the first . This raises the false-positive rate far above 5% (the Challenge exercises measure how much). Fix the sample size in advance, or use a sequential test: a design whose thresholds allow repeated looks while keeping the false-positive rate at α.
- Skipping the SRM check. A broken split makes every later number meaningless.
- Picking the “best” segment after the fact and reporting it as the result.
- Reporting only “significant, p = 0.013”. Report the lift, its CI and the decision rule.
Example 7 — Explain house prices with OLS regression
Section titled “Example 7 — Explain house prices with OLS regression”Goal: The real-estate team asks: “How much does an extra bedroom add to the price?” Fit regressions with the statsmodels formula API, find the confounder in the naive answer and read the coefficients of a better model.
Step 1 — Fit the naive model
Section titled “Step 1 — Fit the naive model”naive = smf.ols("price ~ bedrooms", data=houses).fit()print(naive.params.round(0))print(f"bedrooms: SE {naive.bse['bedrooms']:,.0f}, t = {naive.tvalues['bedrooms']:.1f}")print(f"R-squared {naive.rsquared:.3f}")Intercept 4816.0bedrooms 156348.0dtype: float64bedrooms: SE 3,564, t = 43.9R-squared 0.391The naive answer: each extra bedroom adds about 156,000 USD. A t value of 44 means a p-value so small that it prints as 0. The model explains 39% of the variance of price.
Step 2 — Add the size of the house
Section titled “Step 2 — Add the size of the house”with_size = smf.ols("price ~ bedrooms + sqft", data=houses).fit()coefs = pd.DataFrame( {"coef": with_size.params, "se": with_size.bse, "p": with_size.pvalues})print(coefs.round(4))print(f"corr(bedrooms, sqft) = {houses['bedrooms'].corr(houses['sqft']):.3f}") coef se pIntercept -131083.861 11169.688 0.00bedrooms 3907.368 5936.393 0.51sqft 320.882 10.629 0.00corr(bedrooms, sqft) = 0.851Once the model holds the square footage fixed, an extra bedroom adds only about 3,900 USD, and the p-value of 0.51 shows no evidence of any effect. Size is the confounder: big houses have more bedrooms and cost more. The naive coefficient measured “bigger house”, not “extra bedroom”. Turning a study into a bedroom, at the same size, would not add 156,000 USD.
Step 3 — Fit a log model with neighborhoods
Section titled “Step 3 — Fit a log model with neighborhoods”formula = ( "np.log(price) ~ np.log(sqft) + C(neighborhood) + condition" " + has_pool + distance_to_center_km")model = smf.ols(formula, data=houses).fit()ci = model.conf_int()table = pd.DataFrame({ "coef": model.params, "se": model.bse, "p": model.pvalues, "ci_low": ci[0], "ci_high": ci[1],})print(table.round(4))print( f"R-squared {model.rsquared:.3f}, adjusted {model.rsquared_adj:.3f}" f", n = {model.nobs:.0f}") coef se p ci_low ci_highIntercept 6.483 0.093 0.000 6.302 6.665C(neighborhood)[T.Downtown] 0.514 0.047 0.000 0.421 0.607C(neighborhood)[T.Lakeview] 0.904 0.030 0.000 0.845 0.963C(neighborhood)[T.Maple Grove] 0.369 0.020 0.000 0.330 0.409C(neighborhood)[T.Oak Hill] 0.797 0.026 0.000 0.747 0.848C(neighborhood)[T.Old Town] 0.494 0.047 0.000 0.402 0.585C(neighborhood)[T.Riverside] 0.559 0.039 0.000 0.482 0.636C(neighborhood)[T.Westfield] 0.063 0.015 0.000 0.033 0.093np.log(sqft) 0.754 0.011 0.000 0.733 0.775condition 0.126 0.004 0.000 0.118 0.134has_pool 0.104 0.012 0.000 0.080 0.127distance_to_center_km -0.001 0.003 0.717 -0.007 0.005R-squared 0.865, adjusted 0.865, n = 3000C(neighborhood) creates one dummy variable per neighborhood except the reference level: 7 dummies for 8 neighborhoods. Cedar Park, first in alphabetical order, is the reference level, so each C(neighborhood)[T.…] coefficient compares that neighborhood with Cedar Park at the same size, condition and distance. The model explains 87% of the variance of log price.
Step 4 — Interpret the coefficients
Section titled “Step 4 — Interpret the coefficients”elasticity = model.params["np.log(sqft)"]pool = model.params["has_pool"]cond = model.params["condition"]lake = model.params["C(neighborhood)[T.Lakeview]"]print(f"+10% sqft -> {100 * (1.10**elasticity - 1):+.1f}% price")print(f"pool -> {100 * (np.exp(pool) - 1):+.1f}% price")print(f"+1 condition -> {100 * (np.exp(cond) - 1):+.1f}% price")print(f"Lakeview vs Cedar Park -> {100 * (np.exp(lake) - 1):+.0f}% price")+10% sqft -> +7.4% pricepool -> +10.9% price+1 condition -> +13.4% priceLakeview vs Cedar Park -> +147% priceIn a log-log model, the coefficient of np.log(sqft) is an elasticity: the percent change in price for a 1% change in size. About 0.75 means diminishing returns: 10% more space adds about 7.4% to the price. For a 0/1 predictor in a log model, is the percent effect: a pool adds about 11%. These are associations in observational data, adjusted only for the variables in the model.
Step 5 — Check the residuals
Section titled “Step 5 — Check the residuals”resid, fitted = model.resid, model.fittedvaluesprint( f"residual mean {resid.mean():.4f}, sd {resid.std():.4f}" f", skew {resid.skew():.2f}")by_quartile = resid.groupby(pd.qcut(fitted, 4, labels=["Q1", "Q2", "Q3", "Q4"]))print("residual mean by fitted quartile:", by_quartile.mean().round(3).to_dict())print("residual sd by fitted quartile: ", by_quartile.std().round(3).to_dict())fig, ax = plt.subplots(figsize=(8, 4))ax.scatter(fitted, resid, s=6, alpha=0.4, color="#4c78a8")ax.axhline(0, color="#c0392b")ax.set(title="Residuals vs fitted", xlabel="fitted log(price)", ylabel="residual")plt.show()residual mean 0.0000, sd 0.1924, skew 0.26residual mean by fitted quartile: {'Q1': 0.053, 'Q2': -0.029, 'Q3': -0.051, 'Q4': 0.027}residual sd by fitted quartile: {'Q1': 0.174, 'Q2': 0.172, 'Q3': 0.184, 'Q4': 0.218}
OLS residuals always average 0 overall when the model has an intercept, but not necessarily within each range of fitted values. Here they average about +0.05 in the cheapest quarter, −0.03 to −0.05 in the middle and +0.03 in the most expensive quarter: the band bends slightly upward at both ends. That is a mild violation of linearity. The model leaves out real structure, such as the U-shaped effect of the house’s age and a size effect that differs by neighborhood. The spread is not quite constant either: the residual sd is 0.17 to 0.18 in the lower three quartiles and 0.22 in the top quartile. That is mild heteroscedasticity. A residual sd of about 0.19 on the log scale means typical errors of roughly ±19%. The synthetic course data was generated with noise of only 0.12 on the log scale, so the model misses some structure: school ratings, the age of the house and a size effect that differs by neighborhood.
Step 6 — Compare classic and robust standard errors
Section titled “Step 6 — Compare classic and robust standard errors”robust = smf.ols(formula, data=houses).fit(cov_type="HC3")se_table = pd.DataFrame( {"coef": model.params, "classic_se": model.bse, "hc3_se": robust.bse})print(se_table.loc[["np.log(sqft)", "condition", "has_pool"]].map("{:.4f}".format))print("same coefficients:", np.allclose(model.params, robust.params)) coef classic_se hc3_senp.log(sqft) 0.7537 0.0107 0.0133condition 0.1261 0.0039 0.0040has_pool 0.1036 0.0119 0.0138same coefficients: TrueHC3 changes only the standard errors, never the coefficients. The robust standard error of the size elasticity is about 25% larger than the classic one, which matches the uneven spread of Step 5. Every coefficient shown is still many standard errors from 0, so the conclusions do not change. When the residual plot shows a fan shape, report HC3 standard errors.
Step 7 — Predict a new house
Section titled “Step 7 — Predict a new house”new_house = pd.DataFrame({ "sqft": [1800], "neighborhood": ["Riverside"], "condition": [3], "has_pool": [0], "distance_to_center_km": [6.0],})pred_log = model.predict(new_house).iloc[0]print(f"predicted price: {np.exp(pred_log):,.0f} USD")predicted price: 471,468 USDpredict applies the same formula, including np.log and the dummy columns, to new rows. Exponentiating a predicted log gives roughly the median price for such a house, not the mean.
Common mistakes:
- Reading a coefficient as causal. The bedroom coefficient changed from 156,000 to 3,900 when one confounder entered. Unmeasured confounders can do the same.
- Interpreting a log-model coefficient as dollars. In
np.log(price) ~ ..., coefficients are (approximately) relative changes. - Forgetting that
smf.olssilently drops rows with missing values in any formula column. Checkmodel.nobs. - Printing
summary()in an automated report and diffing it: its header contains the run date and time.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
np.var(x) and Series.var() mixed |
Two “variances” of the same data differ | NumPy uses ddof=0, pandas ddof=1; pass ddof=1 |
| Mean of skewed money data as “typical” | “Typical” price far above most houses | Report the median and IQR; analyze the log |
stats.ttest_ind(a, b) with default settings |
Wrong p-value when variances differ | equal_var=False (Welch) |
| Unpaired test on paired data | Large p-value despite consistent changes | stats.ttest_rel or a one-sample test on differences |
1 - p read as “probability H1 is true” |
Overconfident claims | p assumes H0; report the effect size and CI |
| p > 0.05 read as “no effect” | Good ideas dropped | Report the CI and the power for the MDE |
| Testing many segments or metrics | A “significant” segment that never replicates | Pre-register the primary metric; BH or Bonferroni |
| Peeking at a running A/B test | False-positive rate far above α | Fix n in advance, or use a sequential design |
| No SRM check | A/B results from a broken split | stats.chisquare on the group counts |
| Wald interval for a small proportion | Interval below 0 or too narrow | proportion_confint(..., method="wilson") |
rvs() or bootstrap() without a seed |
Different numbers on every run | random_state=42 / rng=np.random.default_rng(42) |
chi2_contingency on raw rows |
Error or nonsense | Pass a pd.crosstab of counts |
| Large χ² read as a strong relationship | Weak effects look important in big data | Cramér’s V or the odds ratio |
| Correlation read as causation | Wrong business decisions | Randomize, or adjust for confounders and say so |
| Trusting a t-interval on small skewed samples | Real coverage far below 95% | Simulate the coverage; use more data, logs or a BCa bootstrap |
| Skipping the assumption checks | p-values and CIs that do not mean what they say | Q-Q plot, Levene’s test, residuals vs fitted; Welch and HC3 by default |
Printing model.summary() in a checked script |
Output changes every run (date and time) | Print params, bse, pvalues, rsquared |
| Odds ratio read as a risk ratio | Effects overstated for common events | Report both, or the difference in rates |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web products: every large website runs A/B tests on layouts, prices and emails, with the same z-test, SRM check and power analysis as Example 6.
- Performance engineering: benchmark timings are skewed, so engineers compare two builds with a Mann–Whitney test or a bootstrap CI of the median latency instead of eyeballing two numbers.
- Operations and monitoring: a Poisson model of errors per minute sets an alert threshold with
stats.poisson.ppf(0.999, mu); an SRE (site reliability engineer) checks for overdispersion first. - Manufacturing and testing: quality control uses binomial tests for defect rates, and flaky-test triage in CI pipelines asks whether a failure rate rose more than chance would explain.
Summary
Section titled “Summary”- Describe a variable by center, spread and shape. Use the median and IQR for skewed data.
ddof=1gives the sample variance; NumPy defaults toddof=0, pandas toddof=1. scipy.statsdistributions share one interface:pmf/pdf,cdf,sf,ppf,intervalandrvs(random_state=...). Check a distribution against the data before you trust it.- The standard error measures how much a statistic varies between samples. The CLT makes sample means approximately normal for large enough , even for skewed data.
- A 95% confidence interval comes from a method that captures the true parameter 95% of the time. Use t-intervals for means, Wilson for proportions and the bootstrap for anything else.
- A p-value is the probability of data at least as extreme as yours if H0 is true. It is not the probability that H0 is true. α is the Type I error rate; power is .
- Choose the test by the question and the data: Welch, paired or one-sample t-tests; chi-square; ANOVA or Kruskal–Wallis; Mann–Whitney. Report effect sizes and CIs, not only p-values.
- Plan the sample size with a power analysis for the MDE. Correct for multiple tests with Bonferroni or BH. Do not peek.
- Check assumptions with plots first: a Q-Q plot for normality, Levene’s test for equal variances, residuals against fitted values for OLS. Prefer Welch’s test and HC3 standard errors, which stay valid when variances differ.
- Correlation is not causation: randomize when you can, adjust for confounders when you cannot. Read OLS through
params,bse,pvalues,conf_int()andrsquared.
Self-check questions
Section titled “Self-check questions”Q1. A column of six readings gives np.var(x) = 0.37 and pd.Series(x).var() = 0.45. Why do they differ, and which is the sample variance?
Answer
NumPy divides by (ddof=0) and pandas by (ddof=1). The ratio is . The pandas value, with ddof=1, is the unbiased sample variance. Use np.var(x, ddof=1) to get it from NumPy.
Q2. House prices have a mean of 476,000 USD and a median of 376,000 USD. What does this tell you about the shape, and which number should a listing site show as “typical”?
Answer
The mean is well above the median, so the distribution is right-skewed: a few very expensive houses pull the mean up. Show the median as the typical price; it is robust to the extreme values.
Q3. For d = stats.binom(n=200, p=0.10), which call gives the probability of 30 or more buyers?
Answer
d.sf(29). For a discrete distribution, , and sf(k) is . d.sf(30) would give . 1 - d.cdf(29) is the same value as d.sf(29), but less precise in the far tail.
Q4. State the central limit theorem in one sentence. Does it make a sample of 10,000 prices normally distributed?
Answer
For large enough samples of independent observations with a finite variance, the sampling distribution of the mean is approximately normal with mean and standard deviation . No: the 10,000 prices keep their skewed shape. Only the mean of such samples, over repeated sampling, is approximately normal.
Q5. A report says: “The 95% CI for mean monthly charges is 60.4 to 66.8 USD, so there is a 95% probability that the true mean is in this range.” What is wrong, and what is the correct reading?
Answer
The true mean is a fixed number; it is either in this interval or not. The 95% describes the method: intervals built this way contain the true mean in 95% of repeated samples. Correct reading: “We are 95% confident that the true mean lies between 60.4 and 66.8 USD”, meaning the procedure is right 95% of the time.
Q6. An A/B test gives p = 0.03. Which statements are correct? (a) There is a 3% chance that the new version has no effect. (b) If the versions were identical, a difference at least this large would appear about 3% of the time. (c) The effect is large. (d) At α = 0.05, we reject H0.
Answer
(b) and (d). (a) inverts the condition: the p-value assumes H0 is true and cannot be its probability. (c) is not implied: with large samples, small effects get small p-values. Look at the effect size and its CI.
Q7. What are a Type I error and a Type II error in an A/B test, and which quantity sets each one’s probability?
Answer
A Type I error is a false positive: you launch a page that has no real effect. Its probability is α, set before the test. A Type II error is a false negative: you miss a real improvement. Its probability is β = 1 − power, which depends on the effect size, the sample size, the noise and α.
Q8. You measure the same 12 stores’ revenue in 2023 and 2024. Why is ttest_rel correct and ttest_ind wrong here?
Answer
The two measurements of a store are paired: they belong to the same unit. ttest_rel tests the within-store differences, which removes the large differences between big and small stores from the noise. ttest_ind treats the 24 numbers as independent groups, so the between-store spread hides a consistent growth (p = 0.22 instead of a p-value below 0.0001 in this data).
Q9. When do you use Kruskal–Wallis instead of one-way ANOVA? What does a significant result of either test tell you?
Answer
Use Kruskal–Wallis when the groups are strongly skewed, have outliers or are ordinal (ratings), especially with small groups. A significant result says only that at least one group differs from the others. A post hoc test (for example Tukey’s HSD after ANOVA) finds which pairs differ while it controls the false alarms.
Q10. A team plans an A/B test to detect a lift from 10% to 11% conversion. Roughly how many users per group do they need for 80% power at α = 0.05, compared with a lift to 12%? Why?
Answer
About 14,700 per group for 10% → 11%, against about 3,800 for 10% → 12%. Halving the effect needs about four times as many users, because the standard error shrinks only with .
Q11. You test 20 segments of an A/B test at α = 0.05, and one has p = 0.03. Why should you not report it as a finding?
Answer
With 20 tests and no real effects, the chance of at least one p ≤ 0.05 is about 64%. One small p-value among 20 is what chance alone produces. After a Bonferroni correction (0.05 / 20 = 0.0025) or BH, p = 0.03 is not significant. Treat it as a hypothesis for a new test.
Q12. In smf.ols("price ~ bedrooms", ...), the bedroom coefficient is 156,000 USD. In price ~ bedrooms + sqft, it is 3,900 USD with p = 0.51. Explain the change.
Answer
Square footage is a confounder: larger houses have more bedrooms and higher prices. Without sqft, the bedroom coefficient absorbs the effect of size. With sqft in the model, it measures the effect of one more bedroom at the same size, which is close to zero.
Q13. Why should a checked report not print model.summary(), and what should it print instead?
Answer
The summary header contains the current date and time, so the output changes on every run and cannot be compared with a stored expected output. Print the parts you need: model.params, model.bse, model.pvalues, model.conf_int(), model.rsquared and model.nobs, rounded.
Q14. A residual-vs-fitted plot of a regression shows a fan: the residuals spread more for large fitted values. Which OLS assumption fails, what does it break, and what do you do?
Answer
Constant error variance (homoscedasticity) fails: the errors are heteroscedastic. The coefficients stay unbiased, but the classic standard errors, p-values and CIs are wrong. Refit with .fit(cov_type="HC3") for robust standard errors, or model the outcome on a log scale, which often evens out the spread.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 29 exercises with hints and full solutions, from descriptive statistics to power simulations.
- Mini-project: write a statistical report on what drives customer churn.
- Cheat sheet: distributions, tests, effect sizes, power and OLS on one page.
- Next module: 30. SQL for data analysis queries the same data with SQLite and DuckDB: SELECT, GROUP BY, JOINs and window functions.
- Go deeper later: 48. Probability, Bayesian statistics and information theory and 49. Causal inference, GLMs and advanced experimentation cover Bayesian A/B testing, MCMC, KL divergence, causal DAGs, IPW, CUPED, Negative Binomial GLMs and survival curves.