Skip to content

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 np
import pandas as pd
import statsmodels.formula.api as smf
from scipy import stats
from statsmodels.stats.multitest import multipletests
from statsmodels.stats.power import NormalIndPower, TTestIndPower
from 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")
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()
Statistic Formula pandas Robust?
mean xˉ=1n∑xi\bar{x} = \frac{1}{n}\sum x_i s.mean() no
median middle value s.median() yes
sample variance s2=1n−1∑(xi−xˉ)2s^2 = \frac{1}{n-1}\sum (x_i - \bar{x})^2 s.var() no
standard deviation s=s2s = \sqrt{s^2} s.std() no
IQR Q3−Q1Q_3 - Q_1 s.quantile(.75) - s.quantile(.25) yes
coefficient of variation s/xˉs / \bar{x} 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))
Output
0.3714 0.4457 0.4457
0.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
Method Discrete Continuous Returns
pmf(k) yes — P(X=k)P(X = k)
pdf(x) — yes density
cdf(x) yes yes P(X≤x)P(X \le x)
sf(x) yes yes P(X>x)P(X > x)
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) μ\mu σ2\sigma^2
Binomial stats.binom(n, p) npnp np(1−p)np(1-p)
Poisson stats.poisson(mu=lam) λ\lambda λ\lambda
t stats.t(df) 0 dfdf−2\frac{df}{df-2} (df > 2)
Uniform stats.uniform(loc=a, scale=b - a) a+b2\frac{a+b}{2} (b−a)212\frac{(b-a)^2}{12}
Exponential stats.expon(scale=1 / lam) 1/λ1/\lambda 1/λ21/\lambda^2
Log-normal stats.lognorm(s=sigma, scale=np.exp(mu)) eμ+σ2/2e^{\mu + \sigma^2/2} —
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 hours
print(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))
Output
0.0228
0.0163
8.0
2.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: SE=s/n\text{SE} = s / \sqrt{n}. Four times the data halves it.
  • Central limit theorem: for independent data with finite variance, xˉ\bar{x} is approximately N(μ,σ2/n)N(\mu, \sigma^2/n) for large nn. 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 xˉ±t0.975,n−1 s/n\bar{x} \pm t_{0.975,n-1}\, s/\sqrt{n} stats.t.interval(0.95, n - 1, loc=m, scale=se)
Wald, proportion p^±1.96p^(1−p^)/n\hat{p} \pm 1.96\sqrt{\hat{p}(1-\hat{p})/n} 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 Δ±ts12/n1+s22/n2\Delta \pm t\sqrt{s_1^2/n_1 + s_2^2/n_2} 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))
Output
[60.4 66.77]
[0.1461 0.2554]
58.15 62.69

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 p≤αp \le \alpha (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 t=(xˉ−μ0)/(s/n)t = (\bar{x} - \mu_0) / (s/\sqrt{n}), df =n−1= n - 1
Welch t t=(xˉ1−xˉ2)/s12/n1+s22/n2t = (\bar{x}_1 - \bar{x}_2) / \sqrt{s_1^2/n_1 + s_2^2/n_2}
paired t one-sample t on the differences did_i
two-proportion z z=(p^1−p^2)/p^(1−p^)(1/n1+1/n2)z = (\hat{p}_1 - \hat{p}_2) / \sqrt{\hat{p}(1-\hat{p})(1/n_1 + 1/n_2)}, pooled p^\hat{p}
chi-square χ2=∑(O−E)2/E\chi^2 = \sum (O - E)^2 / E, E=row×col/nE = \text{row} \times \text{col} / n, df =(r−1)(c−1)= (r-1)(c-1)
one-way ANOVA FF = between-group variance / within-group variance
churn = customers["churned"] == 1
a = customers.loc[churn, "monthly_charges"]
b = customers.loc[~churn, "monthly_charges"]
print(f"Levene p = {stats.levene(a, b).pvalue:.1e}") # equal variances? no -> Welch
print(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}")
Output
Levene p = 4.8e-16
Welch p = 4.7e-15
Mann-Whitney p = 3.4e-13
chi2 = 439.7, df = 2, p = 3.3e-96
ANOVA p = 0.213
Kruskal p = 0.239
Effect size Formula Rough scale
Cohen’s d (xˉ1−xˉ2)/sp(\bar{x}_1 - \bar{x}_2) / s_p 0.2 small, 0.5 medium, 0.8 large
difference in rates p^1−p^2\hat{p}_1 - \hat{p}_2 (percentage points) business context
relative lift (p^1−p^2)/p^2(\hat{p}_1 - \hat{p}_2) / \hat{p}_2 business context
odds ratio p1/(1−p1)p2/(1−p2)\frac{p_1/(1-p_1)}{p_2/(1-p_2)} 1 = no effect
Cramér’s V χ2/(n(min⁡(r,c)−1))\sqrt{\chi^2 / (n(\min(r, c) - 1))} 0.1 weak, 0.3 moderate, 0.5 strong (for 2-column tables; lower thresholds for larger tables)
Mann–Whitney probability U/(n1n2)U / (n_1 n_2) 0.5 = no tendency
Cohen’s h (proportions) 2arcsin⁡p1−2arcsin⁡p22\arcsin\sqrt{p_1} - 2\arcsin\sqrt{p_2} 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 h
print(round(h_hand, 4), round(proportion_effectsize(0.12, 0.10), 4))
Output
0.313
0.297
6.22
0.064 0.064

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))))
Output
3835
0.892
64
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)
  • mm independent tests at α = 0.05 with no real effects: P(at least one false positive) =1−0.95m= 1 - 0.95^m (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() # rejections
n_bh = multipletests(p, method="fdr_bh")[0].sum()
print(n_bonf, n_bh)
print(np.round(stats.false_discovery_control(p), 3))
Output
1 2
[0.008 0.032 0.067 0.067 0.067 0.08 0.085 0.205]
  1. Choose the primary metric, the MDE, α and power. Compute n per group. Write it down.
  2. Randomize users. Run until n is reached. Do not peek and stop early.
  3. Check for a sample ratio mismatch: stats.chisquare(group_counts).
  4. Test the primary metric: proportions_ztest (rates) or Welch (means).
  5. Report the lift with a CI: absolute (pp) and relative.
  6. Compare the CI with the break-even point: practical significance.
  7. Check guardrail metrics (revenue, refunds, latency).
  8. 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")
Output
SRM p = 0.968
z = 2.486, p = 0.0129, lift CI 0.33 to 2.77 pp
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")
Output
{'np.log(sqft)': 0.7556, 'has_pool': 0.0972}
[0.731, 0.78] 0.819
pool: +10.2% price

In a log-outcome model, a 0/1 predictor with coefficient β\beta changes yy by 100(eβ−1)%100(e^{\beta} - 1)\%.

  • 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”.
  • np.std(x) is the population sd (ddof=0); pandas .std() is the sample sd (ddof=1).
  • scipy.stats.skew uses the biased formula by default; pandas .skew() is bias-corrected.
  • For discrete distributions, P(X≥k)P(X \ge k) is sf(k - 1), not sf(k).
  • stats.ttest_ind defaults to equal_var=True (Student). Pass equal_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_contingency applies 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.
  • mannwhitneyu returns U for the first sample; the order of arguments sets the direction of U/(n1n2)U/(n_1 n_2).
  • stats.bootstrap needs a tuple of samples: (x,). Pass rng= for repeatable results.
  • stats.contingency.odds_ratio expects [[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.ols drops rows with missing values silently. Check nobs.
  • 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.