29. Statistics and probability — Cheat sheet
The essentials of module 29 on one page. Every runnable block on this page is checked against its output. The blocks share one session:
import numpy as npimport pandas as pdimport statsmodels.formula.api as smffrom scipy import statsfrom statsmodels.stats.multitest import multipletestsfrom statsmodels.stats.power import NormalIndPower, TTestIndPowerfrom statsmodels.stats.proportion import ( confint_proportions_2indep, proportion_confint, proportion_effectsize, proportions_ztest,)
customers = pd.read_csv("data/customers.csv")houses = pd.read_csv("data/houses.csv")ab = pd.read_csv("data/ab_test.csv")Quick lookup
Section titled “Quick lookup”| I want to… | Use… |
|---|---|
| mean, median, mode | s.mean(), s.median(), s.mode() (a Series) |
| sample variance / sd | s.var(), s.std() (pandas: ddof=1); NumPy: np.var(x, ddof=1) |
| IQR | stats.iqr(x) or s.quantile(0.75) - s.quantile(0.25) |
| skewness, excess kurtosis | s.skew(), s.kurt() |
| standard error of a mean | stats.sem(x) |
| probability of a value range | dist.cdf(b) - dist.cdf(a) |
tail probability P(X > x) |
dist.sf(x) |
| a percentile of a distribution | dist.ppf(q) |
| random draws, repeatable | dist.rvs(size=n, random_state=42) |
| CI for a mean | stats.t.interval(0.95, df=n - 1, loc=x.mean(), scale=stats.sem(x)) |
| CI for a proportion | proportion_confint(k, n, method="wilson") |
| CI for any statistic | stats.bootstrap((x,), np.median, rng=np.random.default_rng(42)) |
| compare a mean with a target | stats.ttest_1samp(x, popmean=m) |
| compare two group means | stats.ttest_ind(a, b, equal_var=False) (Welch) |
| compare before/after on the same units | stats.ttest_rel(after, before) |
| compare two skewed groups | stats.mannwhitneyu(a, b, alternative="two-sided") |
| compare 3+ group means | stats.f_oneway(*groups); skewed: stats.kruskal(*groups) |
| which pairs differ after ANOVA | stats.tukey_hsd(*groups) |
| relate two categorical variables | stats.chi2_contingency(pd.crosstab(a, b)) |
| check a split or expected shares | stats.chisquare(observed, f_exp=expected) |
| small 2×2 table | stats.fisher_exact(table) |
| compare two conversion rates | proportions_ztest([k1, k2], [n1, n2]) |
| CI for a difference of rates | confint_proportions_2indep(k1, n1, k2, n2, method="newcomb") |
| strength of a categorical link | stats.contingency.association(table, method="cramer") |
| odds ratio with CI | stats.contingency.odds_ratio(table_2x2) |
| sample size for an A/B test | NormalIndPower().solve_power(effect_size=h, alpha=0.05, power=0.8) |
| adjust many p-values | multipletests(p, method="fdr_bh") or stats.false_discovery_control(p) |
| correlation with a p-value | stats.pearsonr(x, y), stats.spearmanr(x, y) |
| check normality by eye | stats.probplot(x, dist="norm") (Q-Q plot) |
| check equal variances | stats.levene(a, b) |
| robust OLS standard errors | smf.ols(...).fit(cov_type="HC3") |
| stratified sample | df.groupby("stratum").sample(frac=0.04, random_state=42) |
| regression with inference | smf.ols("y ~ x1 + C(cat)", data=df).fit() |
Descriptive statistics
Section titled “Descriptive statistics”| Statistic | Formula | pandas | Robust? |
|---|---|---|---|
| mean | s.mean() |
no | |
| median | middle value | s.median() |
yes |
| sample variance | s.var() |
no | |
| standard deviation | s.std() |
no | |
| IQR | s.quantile(.75) - s.quantile(.25) |
yes | |
| coefficient of variation | s.std() / s.mean() |
no | |
| skewness | 0 symmetric, > 0 right tail | s.skew() |
no |
| excess kurtosis | 0 for the normal | s.kurt() |
no |
x = np.array([19.5, 20.7, 20.1, 21.2, 21.2, 20.8])print(round(np.var(x), 4), round(np.var(x, ddof=1), 4), round(pd.Series(x).var(), 4))print(round(stats.sem(x), 4), round(np.std(x, ddof=1) / np.sqrt(len(x)), 4))0.3714 0.4457 0.44570.2725 0.2725| Library | Default ddof |
|---|---|
NumPy np.var, np.std, arr.std() |
0 (population) |
pandas Series.var, .std, DataFrame.describe |
1 (sample) |
statistics.variance / pvariance |
1 / 0 |
scipy.stats.sem |
1 |
Distributions
Section titled “Distributions”| Method | Discrete | Continuous | Returns |
|---|---|---|---|
pmf(k) |
yes | — | |
pdf(x) |
— | yes | density |
cdf(x) |
yes | yes | |
sf(x) |
yes | yes | |
ppf(q) |
yes | yes | inverse CDF (quantile) |
interval(c) |
yes | yes | central range with probability c |
mean(), std(), var() |
yes | yes | moments |
rvs(size, random_state) |
yes | yes | random draws |
| Distribution | scipy | Mean | Variance |
|---|---|---|---|
| Normal | stats.norm(loc=mu, scale=sigma) |
||
| Binomial | stats.binom(n, p) |
||
| Poisson | stats.poisson(mu=lam) |
||
| t | stats.t(df) |
0 | (df > 2) |
| Uniform | stats.uniform(loc=a, scale=b - a) |
||
| Exponential | stats.expon(scale=1 / lam) |
||
| Log-normal | stats.lognorm(s=sigma, scale=np.exp(mu)) |
— | |
| Chi-square | stats.chi2(df) |
df | 2 df |
print(round(stats.norm(21, 0.5).sf(22), 4)) # P(reading > 22)print(round(stats.binom(200, 0.10).sf(29), 4)) # P(30 or more buyers): sf(k - 1)print(stats.poisson(3).ppf(0.99)) # tickets exceeded in 1% of hoursprint(round(stats.t(9).ppf(0.975), 3), round(stats.norm.ppf(0.975), 3))print(stats.norm(0, 1).rvs(size=3, random_state=42).round(3))0.02280.01638.02.262 1.96[ 0.497 -0.138 0.648]Sampling, standard error and confidence intervals
Section titled “Sampling, standard error and confidence intervals”- Standard error of the mean: . Four times the data halves it.
- Central limit theorem: for independent data with finite variance, is approximately for large . Heavy right tails need hundreds of rows.
- 95% CI: the method captures the true parameter in 95% of repeated samples. Not “95% probability for this interval”.
| Interval | Formula | Code |
|---|---|---|
| t, mean | stats.t.interval(0.95, n - 1, loc=m, scale=se) |
|
| Wald, proportion | proportion_confint(k, n, method="normal") (avoid for small n) |
|
| Wilson, proportion | (score interval) | proportion_confint(k, n, method="wilson") |
| Clopper–Pearson | (exact) | proportion_confint(k, n, method="beta") |
| Welch, difference of means | stats.ttest_ind(a, b, equal_var=False).confidence_interval() |
|
| difference of rates | Newcombe | confint_proportions_2indep(k1, n1, k2, n2, method="newcomb") |
| bootstrap | resample, recompute | stats.bootstrap((x,), stat, n_resamples=5_000, rng=rng) |
x = customers.sample(n=200, random_state=42)["monthly_charges"]print(np.round(stats.t.interval(0.95, len(x) - 1, loc=x.mean(), scale=stats.sem(x)), 2))print(np.round(proportion_confint(39, 200, method="wilson"), 4))boot = stats.bootstrap((x.to_numpy(),), np.median, rng=np.random.default_rng(42))print(round(boot.confidence_interval.low, 2), round(boot.confidence_interval.high, 2))[60.4 66.77][0.1461 0.2554]58.15 62.69Hypothesis tests
Section titled “Hypothesis tests”p-value: the probability, assuming H0 and the test’s assumptions are true, of a test statistic at least as extreme as the observed one. Reject H0 if (chosen in advance). It is not P(H0 is true), not the effect size and not the chance of replication.
| H0 true | H0 false | |
|---|---|---|
| reject | Type I error (rate α) | correct (power = 1 − β) |
| do not reject | correct | Type II error (rate β) |
| Question | Test | Nonparametric |
|---|---|---|
| one mean vs target | ttest_1samp |
wilcoxon(x - m) |
| two independent groups | ttest_ind(..., equal_var=False) |
mannwhitneyu |
| paired measurements | ttest_rel |
wilcoxon(after, before) |
| 3+ groups | f_oneway |
kruskal |
| two proportions | proportions_ztest |
fisher_exact (small n) |
| two categorical variables | chi2_contingency |
fisher_exact (2×2) |
| observed vs expected counts | chisquare |
— |
| two numeric variables | pearsonr |
spearmanr |
| Statistic | Formula |
|---|---|
| one-sample t | , df |
| Welch t | |
| paired t | one-sample t on the differences |
| two-proportion z | , pooled |
| chi-square | , , df |
| one-way ANOVA | = between-group variance / within-group variance |
churn = customers["churned"] == 1a = customers.loc[churn, "monthly_charges"]b = customers.loc[~churn, "monthly_charges"]print(f"Levene p = {stats.levene(a, b).pvalue:.1e}") # equal variances? no -> Welchprint(f"Welch p = {stats.ttest_ind(a, b, equal_var=False).pvalue:.1e}")print(f"Mann-Whitney p = {stats.mannwhitneyu(a, b).pvalue:.1e}")chi = stats.chi2_contingency(pd.crosstab(customers["contract"], customers["churned"]))print(f"chi2 = {chi.statistic:.1f}, df = {chi.dof}, p = {chi.pvalue:.1e}")groups = [g.to_numpy() for _, g in customers.groupby("region")["avg_session_minutes"]]print(f"ANOVA p = {stats.f_oneway(*groups).pvalue:.3f}")print(f"Kruskal p = {stats.kruskal(*groups).pvalue:.3f}")Levene p = 4.8e-16Welch p = 4.7e-15Mann-Whitney p = 3.4e-13chi2 = 439.7, df = 2, p = 3.3e-96ANOVA p = 0.213Kruskal p = 0.239Effect sizes
Section titled “Effect sizes”| Effect size | Formula | Rough scale |
|---|---|---|
| Cohen’s d | 0.2 small, 0.5 medium, 0.8 large | |
| difference in rates | (percentage points) | business context |
| relative lift | business context | |
| odds ratio | 1 = no effect | |
| Cramér’s V | 0.1 weak, 0.3 moderate, 0.5 strong (for 2-column tables; lower thresholds for larger tables) | |
| Mann–Whitney probability | 0.5 = no tendency | |
| Cohen’s h (proportions) | input for power functions |
def cohens_d(a: pd.Series, b: pd.Series) -> float: n1, n2 = len(a), len(b) sp = np.sqrt(((n1 - 1) * a.var() + (n2 - 1) * b.var()) / (n1 + n2 - 2)) return (a.mean() - b.mean()) / sp
table = pd.crosstab(customers["contract"], customers["churned"])print(round(cohens_d(a, b), 3))print(round(stats.contingency.association(table, method="cramer"), 3))print(round(stats.contingency.odds_ratio([[823, 1961], [140, 2076]]).statistic, 2))h_hand = 2 * np.arcsin(np.sqrt(0.12)) - 2 * np.arcsin(np.sqrt(0.10)) # Cohen's hprint(round(h_hand, 4), round(proportion_effectsize(0.12, 0.10), 4))0.3130.2976.220.064 0.064Power and sample size
Section titled “Power and sample size”Power rises with the effect size, the sample size and α, and falls with the noise. Plan for the minimum detectable effect at 80% (or 90%) power. Do not compute “observed power” after a test.
h = proportion_effectsize(0.12, 0.10) # detect 10% -> 12%print(int(np.ceil(NormalIndPower().solve_power(effect_size=h, alpha=0.05, power=0.8))))print(round(NormalIndPower().power(effect_size=h, nobs1=5_000, alpha=0.05), 3))print(int(np.ceil(TTestIndPower().solve_power(effect_size=0.5, alpha=0.05, power=0.8))))38350.89264| Change | Sample size needed |
|---|---|
| halve the effect | × 4 |
| power 80% → 90% | × 1.34 |
| α 0.05 → 0.01 | × 1.49 |
| one-sided instead of two-sided | × 0.79 (only if decided in advance) |
Multiple testing
Section titled “Multiple testing”- independent tests at α = 0.05 with no real effects: P(at least one false positive) (64% for 20 tests).
- Bonferroni: test at α / m. Controls the family-wise error rate. Strict.
- Benjamini–Hochberg: controls the false discovery rate. More power; for screens of many metrics or segments.
- Peeking at a running test is multiple testing too: fix n in advance or use a sequential design.
p = np.array([0.001, 0.008, 0.039, 0.041, 0.042, 0.060, 0.074, 0.205])n_bonf = multipletests(p, method="bonferroni")[0].sum() # rejectionsn_bh = multipletests(p, method="fdr_bh")[0].sum()print(n_bonf, n_bh)print(np.round(stats.false_discovery_control(p), 3))1 2[0.008 0.032 0.067 0.067 0.067 0.08 0.085 0.205]A/B test recipe
Section titled “A/B test recipe”- Choose the primary metric, the MDE, α and power. Compute n per group. Write it down.
- Randomize users. Run until n is reached. Do not peek and stop early.
- Check for a sample ratio mismatch:
stats.chisquare(group_counts). - Test the primary metric:
proportions_ztest(rates) or Welch (means). - Report the lift with a CI: absolute (pp) and relative.
- Compare the CI with the break-even point: practical significance.
- Check guardrail metrics (revenue, refunds, latency).
- Treat segment results as exploratory: BH-correct them.
counts = ab.groupby("group")["converted"].agg(["sum", "count"])k = counts.loc[["treatment", "control"], "sum"].to_numpy()n = counts.loc[["treatment", "control"], "count"].to_numpy()print(f"SRM p = {stats.chisquare(n).pvalue:.3f}")z, p_val = proportions_ztest(k, n)lo, hi = confint_proportions_2indep(k[0], n[0], k[1], n[1], method="newcomb")print(f"z = {z:.3f}, p = {p_val:.4f}, lift CI {100 * lo:.2f} to {100 * hi:.2f} pp")SRM p = 0.968z = 2.486, p = 0.0129, lift CI 0.33 to 2.77 ppstatsmodels OLS
Section titled “statsmodels OLS”| Formula | Meaning |
|---|---|
y ~ x |
intercept + slope |
y ~ x1 + x2 |
two predictors |
y ~ C(cat) |
dummy variables, first level is the reference |
y ~ C(cat, Treatment("B")) |
choose the reference level |
y ~ x1 * x2 |
x1 + x2 + x1:x2 (interaction) |
np.log(y) ~ np.log(x) |
functions inside the formula; coefficient = elasticity |
y ~ I(x ** 2) |
arithmetic inside I() |
y ~ x - 1 |
no intercept |
| Result attribute | Gives |
|---|---|
params, bse |
coefficients, standard errors |
tvalues, pvalues |
tests of “coefficient = 0” |
conf_int(alpha=0.05) |
95% CI per coefficient (columns 0 and 1) |
rsquared, rsquared_adj |
fit |
nobs |
rows used (missing rows dropped) |
resid, fittedvalues |
training residuals and predictions |
predict(new_df) |
predictions for new rows |
summary() |
full table; prints the current date and time |
.fit(cov_type="HC3") |
same coefficients, heteroscedasticity-robust standard errors |
OLS inference assumes linearity, independent errors, constant error variance and (for small samples) roughly normal errors. Plot resid against fittedvalues: you want a flat, even band around 0. A fan shape calls for HC3 standard errors; a curve calls for a better model.
formula = "np.log(price) ~ np.log(sqft) + has_pool + C(neighborhood)"m = smf.ols(formula, data=houses).fit()print(m.params[["np.log(sqft)", "has_pool"]].round(4).to_dict())print(m.conf_int().loc["np.log(sqft)"].round(3).tolist(), round(m.rsquared, 3))print(f"pool: {100 * (np.exp(m.params['has_pool']) - 1):+.1f}% price"){'np.log(sqft)': 0.7556, 'has_pool': 0.0972}[0.731, 0.78] 0.819pool: +10.2% priceIn a log-outcome model, a 0/1 predictor with coefficient changes by .
Correlation and causation
Section titled “Correlation and causation”- A confounder drives both variables; adjust for it (add it to the regression) or randomize.
- A randomized experiment is the most reliable design for ruling out unknown confounders.
- Trending series correlate spuriously. Compare changes, not levels.
- Observational results: write “associated with”, not “causes”.
Gotchas
Section titled “Gotchas”np.std(x)is the population sd (ddof=0); pandas.std()is the sample sd (ddof=1).scipy.stats.skewuses the biased formula by default; pandas.skew()is bias-corrected.- For discrete distributions, is
sf(k - 1), notsf(k). stats.ttest_inddefaults toequal_var=True(Student). Passequal_var=False.- Normality tests (
stats.shapiro) reject harmless departures with thousands of rows and miss real ones with ten. Read a Q-Q plot instead. - With skewed money data, a nominal 95% t-interval can cover far less than 95% even at n = 200. Check by simulation, analyze the log or bootstrap (BCa).
chi2_contingencyapplies Yates’ correction to 2×2 tables by default (correction=True).proportion_confint(..., method="normal")clips the Wald interval at 0 and 1, which hides its bad coverage.mannwhitneyureturns U for the first sample; the order of arguments sets the direction of .stats.bootstrapneeds a tuple of samples:(x,). Passrng=for repeatable results.stats.contingency.odds_ratioexpects [[exposed event, exposed no event], [unexposed event, unexposed no event]].- Boolean index labels:
df.loc[[True, False]]is a mask, not a label lookup. Use string labels. smf.olsdrops rows with missing values silently. Checknobs.- Never diff
model.summary()output: its header has the date and time. - A p-value below α with a tiny effect is not a reason to act. A p-value above α is not proof of no effect.