One sample vs a value
z-test for a mean (σ known)
b = load('bottles')
a = b.loc[b.machine == 'A', 'ml']
z = (a.mean() - 500) / (4 / np.sqrt(len(a))) # σ = 4 is known
print(round(z, 3), round(2 * stats.norm.sf(abs(z)), 4))Only when σ comes from outside the sample (a spec, a long history). Estimating σ from the data? Use the t-test.
One-sample t
a = load('bottles').query("machine == 'A'").ml
res = stats.ttest_1samp(a, 500)
lo, hi = res.confidence_interval(0.95)
print(round(res.statistic, 3), round(res.pvalue, 4), res.df)
print(round(lo, 2), round(hi, 2), round((a.mean() - 500) / a.std(), 2))A mean vs a target, σ unknown. Two-sided by default: alternative='greater' only if planned. Report the interval and d.
Exact binomial test
s = load('signups')
a = s.loc[s.page == 'A', 'signed_up']
res = stats.binomtest(int(a.sum()), len(a), p=0.12)
ci = res.proportion_ci(0.95)
print(int(a.sum()), len(a), round(res.pvalue, 4), round(ci.low, 4), round(ci.high, 4))k successes out of n vs a rate p. Exact at any n. Pass p= (default 0.5); the CI is Clopper–Pearson unless method='wilson'.
One-proportion z
s = load('signups')
a = s.loc[s.page == 'A', 'signed_up']
k, n, p0 = int(a.sum()), len(a), 0.12
z = (k / n - p0) / np.sqrt(p0 * (1 - p0) / n) # SE from p0, not from k/n
print(round(z, 3), round(2 * stats.norm.sf(abs(z)), 4))Large-n shortcut to the binomial test (n·p0 and n·(1−p0) ≥ 10). statsmodels proportions_ztest puts k/n in the SE unless prop_var=p0.
Poisson rate vs a value
w1 = load('calls').query('week == 1').calls
k, mu = int(w1.sum()), 5 * len(w1) # expected: 5 calls an hour
p = 2 * min(stats.poisson.cdf(k, mu), stats.poisson.sf(k - 1, mu))
print(k, mu, round(min(1, p), 4), round(w1.var() / w1.mean(), 2))Counts per unit of time or space vs a rate. Check the variance/mean ratio is near 1: overdispersed counts make p far too small.
Two Poisson rates
c = load('calls')
w1, w2 = c.query('week == 1').calls, c.query('week == 2').calls
r = stats.poisson_means_test(int(w1.sum()), len(w1), int(w2.sum()), len(w2))
print(int(w1.sum()), int(w2.sum()), round(r.statistic, 3), round(r.pvalue, 4))Two total counts with their exposures (hours, km, …). Pass totals and exposures, not the raw rows.
χ² test for a variance
a = load('bottles').query("machine == 'A'").ml
n = len(a)
chi2 = (n - 1) * a.var() / 4**2 # target σ0 = 4
print(round(chi2, 2), round(stats.chi2.sf(chi2, n - 1), 5)) # one-sided: more spread
lo, hi = np.sqrt((n - 1) * a.var() / stats.chi2.ppf([0.975, 0.025], n - 1))
print(round(lo, 2), round(hi, 2))Is the spread above a spec? Very sensitive to non-normal data. pandas .var() is ddof=1 (right here); NumPy .var() is ddof=0.
Sign test for a median
new = load('baskets').query("page == 'new'").spend
d = new - 40 # vs a median of £40
k, n = int((d > 0).sum()), int((d != 0).sum()) # drop exact ties
print(k, n, round(stats.binomtest(k, n, 0.5).pvalue, 4))Only the direction of each value counts: no shape assumption at all. Low power; drop values equal to the target.
Wilcoxon signed-rank (one sample)
new = load('baskets').query("page == 'new'").spend
res = stats.wilcoxon(new - 40)
print(res.statistic, round(res.pvalue, 4), round(new.median(), 2))Median vs a value when the shape is symmetric. Pass the differences from the target; zeros are dropped by default.
Wilcoxon signed-rank (paired)
r = load('training')
res = stats.wilcoxon(r.before, r.after)
print(res.statistic, round(res.pvalue, 4), round((r.before - r.after).median(), 3))Paired data without trusting normality: ranks of the differences. Same as wilcoxon(before - after).
Grubbs' outlier test
x = load('lab')['mg_l'].to_numpy()
n, m, s = len(x), x.mean(), x.std(ddof=1)
G = np.max(np.abs(x - m)) / s
t = stats.t.ppf(1 - 0.05 / (2 * n), n - 2)
G_crit = (n - 1) / np.sqrt(n) * np.sqrt(t**2 / (n - 2 + t**2))
print(round(G, 3), round(G_crit, 3), x[np.argmax(np.abs(x - m))])One suspect point in roughly normal data. Test once, not repeatedly; a flagged point needs a reason before you drop it.
Two groups
Two-sample z (σ known)
b = load('bottles')
a, c = b.query("machine == 'A'").ml, b.query("machine == 'B'").ml
z = (a.mean() - c.mean()) / (4 * np.sqrt(1 / len(a) + 1 / len(c)))
print(round(a.mean() - c.mean(), 2), round(z, 3), round(2 * stats.norm.sf(abs(z)), 4))Rare: both σ known from outside the data. Otherwise use Welch.
Student's pooled t
b = load('baskets')
old, new = b.query("page == 'old'").spend, b.query("page == 'new'").spend
res = stats.ttest_ind(new, old) # equal_var=True by default
print(round(res.statistic, 3), round(res.pvalue, 4), int(res.df))ttest_ind's default pools the variances: wrong when spreads and sizes differ. Prefer Welch unless equal σ is known.
Welch's t (the default)
b = load('baskets')
old, new = b.query("page == 'old'").spend, b.query("page == 'new'").spend
res = stats.ttest_ind(new, old, equal_var=False)
lo, hi = res.confidence_interval(0.95)
print(round(res.statistic, 3), round(res.pvalue, 4), round(res.df, 1))
print(round(lo, 2), round(hi, 2))Two independent means: always pass equal_var=False. Costs almost nothing when spreads are equal.
Effect size: Cohen's d
b = load('baskets')
old, new = b.query("page == 'old'").spend, b.query("page == 'new'").spend
sp = np.sqrt(((len(new) - 1) * new.var() + (len(old) - 1) * old.var()) / (len(new) + len(old) - 2))
print(round((new.mean() - old.mean()) / sp, 3))How big, in pooled SDs. Report it beside every p-value: with large n, tiny differences are significant.
Paired t
r = load('training')
res = stats.ttest_rel(r.before, r.after)
d = r.before - r.after
print(round(res.statistic, 3), round(res.pvalue, 4))
print(round(d.mean(), 3), round(d.mean() / d.std(), 3)) # mean gain, d_zSame units measured twice: a one-sample t on the differences. Using ttest_ind here throws the pairing away.
F-test for two variances
b = load('bottles')
a, c = b.query("machine == 'A'").ml, b.query("machine == 'B'").ml
F, da, dc = a.var() / c.var(), len(a) - 1, len(c) - 1
p = 2 * min(stats.f.sf(F, da, dc), stats.f.cdf(F, da, dc))
print(round(F, 3), round(p, 3), round(stats.levene(a, c).pvalue, 4))Needs normal data, badly: a heavy tail fakes a difference. Levene (center=median) is the robust check.
Pitman–Morgan (paired variances)
r = load('training')
res = stats.pearsonr(r.before + r.after, r.before - r.after)
print(round(res.statistic, 3), round(res.pvalue, 4))
print(round(r.before.std(), 3), round(r.after.std(), 3))Did the spread change between paired measurements? Correlate sums with differences; the F-test assumes independence.
Mann–Whitney U
r = load('ratings')
old, new = r.query("version == 'old'").stars, r.query("version == 'new'").stars
res = stats.mannwhitneyu(new, old)
print(res.statistic, round(res.pvalue, 4))
print(round(res.statistic / (len(new) * len(old)), 3)) # P(new > old) + ½ tiesTwo independent groups by ranks: ordinal or skewed data. It tests P(X > Y), not medians, unless the shapes match.
Mood's median test
r = load('ratings')
old, new = r.query("version == 'old'").stars, r.query("version == 'new'").stars
stat, p, med, table = stats.median_test(new, old)
print(med, round(p, 4), table.tolist())Compares medians with a 2×k table of above / below the grand median. Low power; ties='below' by default.
Two-proportion z
from statsmodels.stats.proportion import proportions_ztest
s = load('signups')
tb = pd.crosstab(s.page, s.signed_up)
z, p = proportions_ztest(tb[1].to_numpy(), tb.sum(axis=1).to_numpy())
chi2 = stats.chi2_contingency(tb, correction=False)[0]
print(round(z, 3), round(p, 4), round(z**2, 3), round(chi2, 3))Two rates. z² is the 2×2 χ² without correction: chi2_contingency applies Yates' correction to 2×2 tables by default.
Permutation test (two groups)
b = load('baskets')
old, new = b.query("page == 'old'").spend.to_numpy(), b.query("page == 'new'").spend.to_numpy()
diff = lambda x, y, axis: np.mean(x, axis=axis) - np.mean(y, axis=axis)
res = stats.permutation_test((new, old), diff, n_resamples=9999, random_state=1)
print(round(diff(new, old, 0), 3), round(res.pvalue, 4))Any statistic, no distribution assumed: shuffle the labels. Give the statistic an axis argument (fast) and fix random_state.
Sign-flip test (paired)
d = load('training').eval('before - after').to_numpy()
res = stats.permutation_test((d,), np.mean, permutation_type='samples', n_resamples=9999, random_state=1)
print(round(d.mean(), 3), round(res.pvalue, 4))Paired data: one sample of differences with permutation_type='samples' flips their signs. Never shuffle across pairs.
Bootstrap interval as a test
new = load('baskets').query("page == 'new'").spend.to_numpy()
boot = stats.bootstrap((new,), np.median, n_resamples=9999, random_state=1)
ci = boot.confidence_interval
print(round(ci.low, 2), round(ci.high, 2), ci.low <= 40 <= ci.high) # is £40 plausible?Resample the data to get an interval for any statistic; a value outside the 95 % CI is rejected at 5 %. Default method is BCa.
Permutation F (many groups)
c = load('clinics')
groups = [g.to_numpy() for _, g in c.groupby('clinic')['wait']]
F = lambda *s: stats.f_oneway(*s).statistic
res = stats.permutation_test(groups, F, n_resamples=1999, vectorized=False, random_state=1)
print(round(F(*groups), 3), round(res.pvalue, 4))ANOVA without the normality assumption: shuffle labels, recompute F. Still assumes exchangeable groups (similar spreads).
Permutation test for r
s = load('study')
r = lambda x: stats.pearsonr(x, s.score).statistic
res = stats.permutation_test((s.hours.to_numpy(),), r, permutation_type='pairings', n_resamples=9999, random_state=1)
print(round(r(s.hours), 3), round(res.pvalue, 4))Correlation without bivariate normality: shuffle the pairings. One sample passed, the other fixed inside the statistic.
Many groups
One-way ANOVA
c = load('clinics')
groups = [g.to_numpy() for _, g in c.groupby('clinic')['wait']]
res = stats.f_oneway(*groups)
print([len(g) for g in groups], round(res.statistic, 3), round(res.pvalue, 4))Any difference among k means, one test instead of many t-tests. Assumes equal spreads: if not, use Welch ANOVA.
Effect size: η²
c = load('clinics')
m = c.groupby('clinic')['wait'].transform('mean')
ss_b, ss_t = ((m - c.wait.mean()) ** 2).sum(), ((c.wait - c.wait.mean()) ** 2).sum()
print(round(ss_b / ss_t, 3))Share of the variation explained by the groups. Report it with the F test.
Welch ANOVA
from statsmodels.stats.oneway import anova_oneway
c = load('clinics')
w = anova_oneway(c['wait'], c['clinic'], use_var='unequal')
print(round(w.statistic, 3), round(w.pvalue, 4), round(w.df[1], 1))The default for k groups when spreads or sizes differ. use_var='unequal' is the default; 'equal' gives the classic F.
Levene · Bartlett
c = load('clinics')
groups = [g.to_numpy() for _, g in c.groupby('clinic')['wait']]
print([round(g.var(ddof=1), 1) for g in groups])
print(f'{stats.levene(*groups).pvalue:.1e}', f'{stats.bartlett(*groups).pvalue:.1e}')Equal spreads? levene's default center='median' (Brown–Forsythe) is robust; Bartlett is exact only for normal data.
Tukey HSD (by hand)
from itertools import combinations
from statsmodels.stats.libqsturng import qsturng
g = load('clinics').groupby('clinic')['wait']; m, n, v = g.mean(), g.count(), g.var()
df = n.sum() - len(n); mse = ((n - 1) * v).sum() / df
q = qsturng(0.95, len(n), df)
for a, b in combinations(m.index, 2):
h = q * np.sqrt(mse / 2 * (1 / n[a] + 1 / n[b]))
print(a, b, round(m[b] - m[a], 2), round(m[b] - m[a] - h, 2), round(m[b] - m[a] + h, 2))Every pair, family error kept at 5 %. An interval missing 0 = a real difference. Assumes equal spreads (pooled MSE).
Dunnett (vs a control)
g = {k: v.to_numpy() for k, v in load('clinics').groupby('clinic')['wait']}
res = stats.dunnett(g['B'], g['C'], g['D'], control=g['A'], random_state=1)
print([round(p, 4) for p in res.pvalue])Each group vs one control only: tighter than Tukey. Pass the control by keyword; fix random_state for stable p.
Planned contrast · Scheffé
g = load('clinics').groupby('clinic')['wait']
m, n, v = g.mean(), g.count(), g.var()
N, k = n.sum(), len(n); mse = ((n - 1) * v).sum() / (N - k)
w = pd.Series({'A': -1/3, 'B': -1/3, 'C': 1, 'D': -1/3}) # weights sum to 0
est, se = (w * m).sum(), np.sqrt(mse * (w**2 / n).sum())
print(round(est, 2), round(2 * stats.t.sf(abs(est / se), N - k), 4)) # planned
print(round(stats.f.sf((est / se)**2 / (k - 1), k - 1, N - k), 4)) # SchefféPlanned before seeing data: a t test. Chosen after looking: Scheffé, which covers every possible contrast.
Is the top group best? (Hsu)
from statsmodels.stats.libqsturng import qsturng
g = load('clinics').groupby('clinic')['wait']; m, n, v = g.mean(), g.count(), g.var()
df = n.sum() - len(n); mse = ((n - 1) * v).sum() / df
best, q = m.idxmin(), qsturng(0.95, len(n), df) / np.sqrt(2) # smallest wait wins
for o in m.index.drop(best):
d, h = m[o] - m[best], q * np.sqrt(mse * (1 / n[o] + 1 / n[best]))
print(best, o, round(d, 2), round(d - h, 2))Is the winner really better than each rival? A lower bound above 0 rules that rival out. Here Tukey q/√2 (conservative).
Kruskal–Wallis
c = load('clinics')
res = stats.kruskal(*[w for _, w in c.groupby('clinic')['wait']])
print(round(res.statistic, 3), round(res.pvalue, 4))
print(c.assign(r=c.wait.rank()).groupby('clinic').r.mean().round(2).to_dict())k groups by ranks: skewed or ordinal data. Like Mann–Whitney it compares rank distributions, not medians.
Dunn's follow-up (Holm)
from statsmodels.stats.multitest import multipletests
c = load('clinics').assign(r=lambda d: d.wait.rank()); N = len(c)
R, n = c.groupby('clinic').r.mean(), c.groupby('clinic').r.count()
tc = c.wait.value_counts(); s2 = N * (N + 1) / 12 - (tc**3 - tc).sum() / (12 * (N - 1))
pairs = [(a, b) for i, a in enumerate(R.index) for b in R.index[i + 1:]]
z = np.array([(R[a] - R[b]) / np.sqrt(s2 * (1 / n[a] + 1 / n[b])) for a, b in pairs])
print([round(p, 4) for p in multipletests(2 * stats.norm.sf(np.abs(z)), method='holm')[1]])Which pairs after Kruskal–Wallis: z on mean ranks from the joint ranking, then a Holm correction.
Friedman
t = load('tasting')
wide = t.pivot(index='taster', columns='recipe', values='score')
res = stats.friedmanchisquare(*[wide[c] for c in wide])
print(round(res.statistic, 2), round(res.pvalue, 4))Same subjects under k conditions, by ranks within each subject. Pass one column per condition, in wide form.
Cochran's Q
from statsmodels.stats.contingency_tables import cochrans_q
liked = load('tasting').pivot(index='taster', columns='recipe', values='liked')
q = cochrans_q(liked.values)
print(liked.sum().tolist(), round(q.statistic, 3), round(q.pvalue, 4))Friedman for yes/no answers: same subjects, k conditions. With two conditions it is McNemar.
Kendall's W
wide = load('judges').pivot(index='judge', columns='entry', values='rank')
m, n = wide.shape # judges, entries
R = wide.sum()
W = 12 * ((R - m * (n + 1) / 2) ** 2).sum() / (m**2 * (n**3 - n))
chi2 = m * (n - 1) * W
print(round(W, 3), round(chi2, 2), round(stats.chi2.sf(chi2, n - 1), 5))Agreement of m judges ranking n items: 0 = none, 1 = perfect. Its test is Friedman with items as the treatments.
Designs with structure
Two-way ANOVA
f = load('fertiliser')
model = smf.ols('kg ~ C(fertiliser) * C(water)', data=f).fit()
table = sm.stats.anova_lm(model, typ=2)
print(table[['F', 'PR(>F)']].round(4))Two factors and their interaction. Read the interaction first: if real, main effects alone mislead. Wrap codes in C().
Unequal cells: Type II vs III
f = load('fertiliser'); u = f.drop(f.index[[6, 7, 8, 9]])
t2 = sm.stats.anova_lm(smf.ols('kg ~ C(fertiliser) * C(water)', data=u).fit(), typ=2)
t3 = sm.stats.anova_lm(smf.ols('kg ~ C(fertiliser, Sum) * C(water, Sum)', data=u).fit(), typ=3)
print(round(t2.loc['C(fertiliser)', 'PR(>F)'], 4), round(t3.loc['C(fertiliser, Sum)', 'PR(>F)'], 4))Unequal cell sizes: typ=1 depends on term order. Type III needs Sum coding, C(x, Sum), or its answers are wrong.
Tukey's non-additivity
Y = load('yields').pivot(index='variety', columns='field', values='t_ha').to_numpy()
a, b = Y.mean(1) - Y.mean(), Y.mean(0) - Y.mean()
ssn = (np.outer(a, b) * Y).sum() ** 2 / ((a ** 2).sum() * (b ** 2).sum())
ssr = ((Y - Y.mean() - a[:, None] - b) ** 2).sum()
df = (len(a) - 1) * (len(b) - 1) - 1
F = ssn / ((ssr - ssn) / df)
print(round(F, 3), round(stats.f.sf(F, 1, df), 4))One value per cell, so no interaction term: this 1-df test checks for a multiplicative one. If it fires, try logs.
Nested ANOVA
d = load('schools')
school = d.groupby('school').score.transform('mean')
cls = d.groupby('class').score.transform('mean')
ms_s = ((school - d.score.mean()) ** 2).sum() / 3 # 4 schools − 1
ms_c = ((cls - school) ** 2).sum() / 8 # 4 × (3 − 1) classes
F = ms_s / ms_c # schools over classes
print(round(ms_s, 2), round(ms_c, 2), round(F, 3), round(stats.f.sf(F, 3, 8), 4))Classes inside schools: test schools against the class mean square, not the pupils. Pupils as n inflates significance.
Random effects: variance components
g = load('machines').groupby('machine').mm
n = 5 # parts per machine
ms_b, ms_w = n * g.mean().var(), g.var().mean()
s2_m = max(0, (ms_b - ms_w) / n) # between-machine variance
print(round(s2_m, 3), round(ms_w, 3), round(s2_m / (s2_m + ms_w), 2)) # ICC
print(round(stats.f_oneway(*[x for _, x in g]).pvalue, 4))Groups sampled from a larger population: estimate how much variance they add (ICC). Balanced design shown.
Hotelling's T² (two groups)
d = load('patients'); cols = ['systolic', 'diastolic']
X, Y = d[d.group == 'drug'][cols].to_numpy(), d[d.group == 'placebo'][cols].to_numpy()
n1, n2, k = len(X), len(Y), 2
diff = X.mean(0) - Y.mean(0)
S = ((n1 - 1) * np.cov(X.T) + (n2 - 1) * np.cov(Y.T)) / (n1 + n2 - 2)
T2 = n1 * n2 / (n1 + n2) * diff @ np.linalg.solve(S, diff)
F = (n1 + n2 - k - 1) / (k * (n1 + n2 - 2)) * T2
print(round(T2, 2), round(F, 3), round(stats.f.sf(F, k, n1 + n2 - k - 1), 4))Several correlated outcomes, one test: no multiple-testing tax, and uses the correlation. Note np.cov wants variables in rows.
Counts and tables
χ² goodness of fit
d = load('blood')
obs = d['type'].value_counts().loc[['O', 'A', 'B', 'AB']].to_numpy()
exp = np.array([0.45, 0.40, 0.11, 0.04]) * obs.sum()
chi2, p = stats.chisquare(obs, exp)
print(obs, round(chi2, 3), round(p, 4), np.round((obs - exp) / np.sqrt(exp), 2))Counts vs a known mix. Expected counts must sum to the total and be ≥ 5; pass ddof= for every parameter you estimated.
χ² independence (r×c)
d = load('commute')
tb = pd.crosstab(d['district'], d['mode'])
chi2, p, dof, exp = stats.chi2_contingency(tb)
print(round(chi2, 3), dof, round(p, 5))
print(((tb - exp) / np.sqrt(exp)).round(2))
print(round(stats.contingency.association(tb, method='cramer'), 3)) # Cramér's VTwo categorical variables from one sample. Read the residuals (beyond ±2) for where; Cramér’s V for how strong.
Fisher's exact test
d = load('pilot')
tb = pd.crosstab(d['arm'], d['recovered']).loc[['new', 'usual'], [1, 0]].to_numpy()
odds, p = stats.fisher_exact(tb)
print(tb.tolist(), round(odds, 2), round(p, 4))
print(round(stats.fisher_exact(tb, alternative='greater')[1], 4))A 2×2 table with small counts (an expected cell under 5). Exact but conservative; barnard_exact has more power.
Homogeneity of proportions
d = load('commute')
t = pd.crosstab(d['district'], d['mode'])
print((t.div(t.sum(axis=1), axis=0) * 100).round(1)) # row % per district
chi2, p, dof, exp = stats.chi2_contingency(t)
print(round(chi2, 3), dof, round(p, 5))Fixed group sizes, one mix each: same arithmetic as independence, a different question. Compare row percentages.
G-test (likelihood ratio)
b = load('blood')
obs = b['type'].value_counts().loc[['O', 'A', 'B', 'AB']].to_numpy()
exp = np.array([0.45, 0.40, 0.11, 0.04]) * 400
r = stats.power_divergence(obs, exp, lambda_='log-likelihood')
c = load('commute'); t = pd.crosstab(c['district'], c['mode'])
g, p = stats.chi2_contingency(t, lambda_='log-likelihood')[:2]
print(round(r.statistic, 3), round(r.pvalue, 4), round(g, 3), round(p, 5))Same job as Pearson χ², but G adds up across nested sub-tables. lambda_='log-likelihood' switches either call to G.
McNemar
from statsmodels.stats.contingency_tables import mcnemar
d = load('debate')
t = pd.crosstab(d.before, d.after).loc[[1, 0], [1, 0]] # rows: before yes, no
r = mcnemar(t.values) # exact=True by default
print(t.values.tolist(), round(r.pvalue, 4))Yes/no asked twice of the same people: only the switchers count. Never chi2_contingency here; it ignores the pairing.
Cochran–Armitage trend
d = load('dose')
g = d.groupby('dose').responded
y, n, x = g.sum().values, g.count().values, np.arange(5)
pbar, xbar = y.sum() / n.sum(), (n * x).sum() / n.sum()
z = (y * (x - xbar)).sum() / np.sqrt(pbar * (1 - pbar) * (n * (x - xbar) ** 2).sum())
print(y.tolist(), round(z, 3), round(2 * stats.norm.sf(abs(z)), 4))A yes/no rate across ordered groups (doses). One df aimed at a trend: far more power than the k−1 df χ².
Mantel–Haenszel (strata)
from statsmodels.stats.contingency_tables import StratifiedTable
a = load('admissions')
tab = lambda g: pd.crosstab(g['group'], g['admitted']).loc[['men', 'women'], [1, 0]].values
st = StratifiedTable([tab(g) for _, g in a.groupby('dept')])
print(round(st.oddsratio_pooled, 3), round(st.test_null_odds(correction=False).pvalue, 4))
print(round(st.test_equal_odds().pvalue, 4)) # Breslow–Day2×2 tables in strata: a common odds ratio that pooling can't reverse (Simpson). Check equal odds across strata first.
Transition test (Markov)
x = load('weather')['rain'].values
T = pd.crosstab(x[:-1], x[1:]) # rows: today, columns: tomorrow
print(T.values.tolist(), (T[1] / T.sum(axis=1)).round(3).tolist())
chi2, p, df, _ = stats.chi2_contingency(T, correction=False)
print(round(chi2, 2), df, f'{p:.1e}')Does today predict tomorrow? Tabulate consecutive pairs and test independence. Pairs overlap, so it needs a long series.
Relationships
Test r (ρ = 0)
d = load('study')
res = stats.pearsonr(d.hours, d.score)
ci = res.confidence_interval()
print(round(res.statistic, 3), round(res.pvalue, 4))
print(round(ci.low, 3), round(ci.high, 3))A straight-line link between two numbers; report r with its interval. Two-sided by default. r ≈ 0 means no straight line, not no link: plot first.
Compare two r: Fisher z
d = load('cities')
r = [stats.pearsonr(g.temp, g.sales).statistic for _, g in d.groupby('city')]
n = d.groupby('city').size().to_numpy()
z = (np.arctanh(r[0]) - np.arctanh(r[1])) / np.sqrt(1 / (n[0] - 3) + 1 / (n[1] - 3))
print(np.round(r, 3), round(z, 3), round(2 * stats.norm.sf(abs(z)), 4))Two r from two independent samples. The SE uses n − 3, not n. Both r from the same people: this test is wrong, use a dependent-r test.
Spearman ρ
d = load('wines')
sp = stats.spearmanr(d.price, d.stars)
print(round(sp.statistic, 3), round(sp.pvalue, 6))Monotone links, ranks, skew or one wild point: Pearson on the ranks. Blind to U shapes; the p is the t approximation, not exact.
Kendall τ
d = load('wines')
kt = stats.kendalltau(d.price, d.stars)
print(round(kt.statistic, 3), round(kt.pvalue, 6))Rank agreement: concordant minus discordant pairs; τ-b handles ties by default. Smaller than ρ on the same data, so never compare the two numbers.
Regression slope t
d = load('study')
fit = stats.linregress(d.hours, d.score)
half = stats.t.isf(0.025, len(d) - 2) * fit.stderr
print(round(fit.slope, 3), round(fit.stderr, 3), round(fit.pvalue, 4))
print(round(fit.slope - half, 3), round(fit.slope + half, 3))How much y changes per unit of x; the same p as the r test. Assumes independent errors: for data in time order check Durbin–Watson first.
Lack-of-fit F
g = load('growth')
line = smf.ols('height ~ dose', data=g).fit()
means = smf.ols('height ~ C(dose)', data=g).fit()
table = sm.stats.anova_lm(line, means)
print(round(table.F.iloc[1], 3), round(table['Pr(>F)'].iloc[1], 5))Is a line enough? Needs repeated x values: the line against one mean per x. List the smaller model first in anova_lm. Small p = it bends.
Regression t & F
h = load('houses')
m = smf.ols('price_k ~ size_m2 + rooms + age', data=h).fit()
print(m.params.round(3).tolist())
print(m.pvalues.round(5).tolist())
print(round(m.fvalue, 2), f'{m.f_pvalue:.0e}', round(m.rsquared, 3))Each t: does this predictor add, given the others? F: does any help? Near-copy predictors (check VIF) give a big F and weak t values.
Durbin–Watson
from statsmodels.stats.stattools import durbin_watson
d = load('monthly')
e = smf.ols('sales ~ adverts', data=d).fit().resid.to_numpy()
rho = (e[1:] * e[:-1]).sum() / (e ** 2).sum()
print(round(durbin_watson(e), 3), round(rho, 3))Residuals in time order: about 2 = no carry-over, well below 2 = positive carry-over and OLS p values too small. Pass the residuals, not y.
A t-test is a regression
b = load('baskets')
fit = smf.ols('spend ~ page', data=b).fit()
t = stats.ttest_ind(b.spend[b.page == 'old'], b.spend[b.page == 'new'])
print(round(fit.params['page[T.old]'], 2), round(fit.pvalues['page[T.old]'], 4), round(t.pvalue, 4))Pooled t, ANOVA and the r test are OLS with a 0/1 or category column. It matches Student’s t (equal_var=True), not Welch.
Wald and likelihood ratio
d = load('dose')
fit = smf.logit('responded ~ dose', data=d).fit(disp=0)
lr = 2 * (fit.llf - fit.llnull)
print('Wald', round(fit.tvalues['dose'], 3), round(fit.pvalues['dose'], 4))
print('LR', round(lr, 3), round(stats.chi2.sf(lr, 1), 4))summary() p values are Wald. The LR test (fit with vs without) is safer for small n or big effects. disp=0 hides the fit log.
Shape and fit
Shapiro–Wilk
x = load('baskets').spend
w, p = stats.shapiro(x)
lw, lp = stats.shapiro(np.log(x))
print(round(w, 4), f'{p:.1e}', round(lw, 4), round(lp, 4))The strongest default normality test. Huge n rejects tiny wobbles, small n passes almost anything: read a Q–Q plot (stats.probplot) too.
KS one-sample
b = load('bottles').query("machine == 'B'").ml
ks = stats.kstest(b, 'norm', args=(500, 4))
print(round(ks.statistic, 3), round(ks.pvalue, 4))Data against a curve fixed in advance (the spec: 500 ml, σ 4). Without args it tests N(0, 1); args from the sample make p far too big.
Lilliefors
from statsmodels.stats.diagnostic import lilliefors
b = load('bottles').query("machine == 'B'").ml
D, p = lilliefors(b, dist='norm')
print(round(D, 3), round(p, 4))KS when the mean and SD come from the data (dist='exp' too). The corrected p is honest, but Shapiro–Wilk has more power for normality.
Anderson–Darling
res = stats.anderson(load('returns').ret, dist='norm')
print(round(res.statistic, 3))
print(res.critical_values.tolist(), res.significance_level.tolist())Weights the tails, so it sees fat tails KS misses. SciPy gives no p: reject at a level when the statistic passes that critical value.
KS two-sample
d = load('couriers')
a, b = d[d.courier == 'swift'].minutes, d[d.courier == 'bolt'].minutes
ks = stats.ks_2samp(a, b)
print(round(ks.statistic, 3), round(ks.pvalue, 5), ks.statistic_location)Any difference between two samples: centre, spread or shape. Weak for a pure centre shift (Mann–Whitney is sharper). Two-sided by default.
K-sample Anderson–Darling
d = load('clinics')
groups = [g.wait.to_numpy() for _, g in d.groupby('clinic')]
ad = stats.anderson_ksamp(groups)
print(round(ad.statistic, 3), round(ad.pvalue, 4))Do k samples share one distribution? SciPy clips the p to 0.001–0.25 and warns when it does. Centres only: Kruskal–Wallis.
Monte-Carlo fit
x = load('gaps').gap.to_numpy()
def ks_fit(y): # gamma by moments, then the KS gap
k, th = y.mean() ** 2 / y.var(ddof=1), y.var(ddof=1) / y.mean()
return stats.kstest(y, 'gamma', args=(k, 0, th)).statistic, k, th
D, k, th = ks_fit(x)
rng = np.random.default_rng(1)
sim = np.array([ks_fit(rng.gamma(k, th, len(x)))[0] for _ in range(500)])
print(round(D, 4), round((np.sum(sim >= D) + 1) / 501, 4))Any fitted curve: simulate from the fit and refit every fake sample the same way. Skip the refit and the p is too big again.
Randomness and order
Runs test
from statsmodels.sandbox.stats.runs import runstest_1samp
q = load('quality').fill.to_numpy()
z, p = runstest_1samp(q, cutoff='median')
print(round(z, 3), round(p, 4))Above/below a cut in time order: too few runs = clumping, too many = alternating. cutoff defaults to 'mean'; pass 'median' for a 50/50 split.
Mann–Kendall + Sen slope
x = load('glacier').retreat.to_numpy()
mk = stats.kendalltau(np.arange(len(x)), x)
i, j = np.triu_indices(len(x), 1)
print(round(mk.statistic, 3), round(mk.pvalue, 4))
print(round(np.median((x[j] - x[i]) / (j - i)), 3))A steady rise or fall: Kendall τ against the time index; Sen’s slope sizes it. Carry-over between steps gives false alarms: prewhiten first.
Ljung–Box / von Neumann
from statsmodels.stats.diagnostic import acorr_ljungbox
q = load('quality').fill.to_numpy()
lb = acorr_ljungbox(q, lags=[10])
print(round(lb.lb_stat.iloc[0], 2), f'{lb.lb_pvalue.iloc[0]:.2g}')
print(round(np.mean(np.diff(q) ** 2) / np.var(q), 3))Carry-over in the first lags (Q) or at lag 1 (von Neumann ratio, 2 if independent). Give lags= yourself, and remove a trend first.
Wald–Wolfowitz runs
from statsmodels.sandbox.stats.runs import runstest_2samp
d = load('couriers')
z, p = runstest_2samp(d[d.courier == 'swift'].minutes, d[d.courier == 'bolt'].minutes)
print(round(z, 3), f'{p:.1e}')Pool and sort two samples: few runs of the labels = they differ somewhere. Ties across groups blur the runs; for a centre shift use Mann–Whitney.
Which population? (LR)
w = load('wings').wing
lr = np.exp(stats.norm.logpdf(w, 66, 3).sum() - stats.norm.logpdf(w, 62, 3).sum())
for prior in [0.05, 0.5]:
print(prior, round(lr, 2), round(lr * prior / (lr * prior + 1 - prior), 3))Two known populations: the likelihood ratio says which fits better; times the prior odds gives posterior odds. Sum logpdf, never multiply pdfs.
Longest streak, shuffled
x = load('shots').hit.to_numpy()
def longest(h):
return max(len(s) for s in ''.join(map(str, h)).split('0'))
rng = np.random.default_rng(1)
sims = np.array([longest(rng.permutation(x)) for _ in range(2000)])
print(longest(x), round(np.mean(sims >= longest(x)), 4))Is a streak longer than shuffling the same hits gives? The shuffle keeps the hit rate. Choose the statistic before looking, or the p means nothing.
Deciding between hypotheses
Neyman–Pearson cut and power
mu0, mu1, se = 500, 502, 4 / np.sqrt(30)
cut = mu0 + stats.norm.isf(0.05) * se # reject H0 above this mean
print(round(cut, 3), round(stats.norm.sf((cut - mu1) / se), 3))
Two exact hypotheses: fix α, reject past the cut; power = the chance H1 data pass it. isf(0.05) is one-sided; use isf(0.025) for two.
Likelihood ratio test by hand
d = load('calls')
rate = d.groupby('week').calls.transform('mean') # each week its own rate
ll2 = stats.poisson.logpmf(d.calls, rate).sum()
ll1 = stats.poisson.logpmf(d.calls, d.calls.mean()).sum()
lr = 2 * (ll2 - ll1)
print(round(lr, 3), round(stats.chi2.sf(lr, 1), 4))Nested models: 2·(log-lik big − log-lik small) ~ χ², df = extra parameters. Sum logpmf/logpdf at the fitted values; trust it for large n.
One- vs two-sided power
se = 4 / np.sqrt(30)
shift = 1.5 / se # a 1.5 ml overfill, in SEs
one = stats.norm.sf(stats.norm.isf(0.05) - shift)
two = stats.norm.sf(stats.norm.isf(0.025) - shift) + stats.norm.cdf(-stats.norm.isf(0.025) - shift)
print(round(one, 3), round(two, 3))
One-sided is most powerful for one direction, if chosen before the data. SciPy tests are two-sided unless alternative= says otherwise.
SPRT: test as the data arrive
x = load('signups').query("page == 'B'").signed_up.to_numpy()
A, B = np.log(0.8 / 0.05), np.log(0.2 / 0.95) # power 0.8, α 0.05
L = np.cumsum(np.where(x == 1, np.log(0.15 / 0.10), np.log(0.85 / 0.90)))
stop = np.argmax((L >= A) | (L <= B))
print(stop + 1, '15 %' if L[stop] >= A else '10 %')Stop the first time the log-LR crosses A = log((1−β)/α) or B = log(β/(1−α)). Check a boundary was crossed: argmax gives 0 if none was.
Peeking: a Pocock bar
rng = np.random.default_rng(1)
z = np.cumsum(rng.standard_normal((20000, 10)), axis=1) / np.sqrt(np.arange(1, 11))
print(round(np.mean((np.abs(z) > 1.96).any(axis=1)), 3)) # 10 naive looks
c = np.quantile(np.abs(z).max(axis=1), 0.95)
print(round(c, 3), round(2 * stats.norm.sf(c), 4))
Ten looks at |z| > 1.96 raise false alarms from 5 % to about 20 %. Pocock: one higher bar at every planned look so the whole run stays at 5 %.
TOST equivalence
from statsmodels.stats.weightstats import ttost_ind
d = load('generic')
gen, brand = d[d.tablet == 'generic'].mg, d[d.tablet == 'brand'].mg
p = ttost_ind(gen, brand, -1.0, 1.0, usevar='unequal')[0]
print(round(gen.mean() - brand.mean(), 3), round(p, 4))Show two means are close: both one-sided tests inside ±margin. Fix the margin first; usevar defaults to 'pooled'. A big p elsewhere proves nothing.
Bayes factor for no difference
d = load('generic')
w = stats.ttest_ind(d[d.tablet == 'generic'].mg, d[d.tablet == 'brand'].mg, equal_var=False)
bf01 = np.sqrt(len(d)) * (1 + w.statistic ** 2 / w.df) ** (-len(d) / 2)
print(round(w.pvalue, 3), round(bf01, 1))BF01 > 1 favours “no difference”: evidence for the null, which p cannot give. This BIC-style factor is rough; above 3 is moderate support.
Circular data
Circular mean + Rayleigh
b = load('homing').query("site == 'north'").bearing
th, n = np.radians(b.to_numpy()), len(b)
R = np.hypot(np.cos(th).mean(), np.sin(th).mean())
p = np.exp(np.sqrt(1 + 4 * n + 4 * (n**2 - (n * R)**2)) - (1 + 2 * n))
print(round(stats.circmean(b, high=360), 1), round(R, 3), round(n * R**2, 2), f'{p:.1e}')One preferred direction, or none? circmean works in radians unless high=360. Two opposite clusters cancel out: double the angles first.
Kuiper (angles vs a curve)
u = np.sort(load('homing').query("site == 'north'").bearing.to_numpy()) / 360
n, i, j = len(u), np.arange(1, len(u) + 1), np.arange(1, 101)
V = np.max(i / n - u) + np.max(u - (i - 1) / n)
lam = (np.sqrt(n) + 0.155 + 0.24 / np.sqrt(n)) * V
p = np.sum(2 * (4 * j**2 * lam**2 - 1) * np.exp(-2 * j**2 * lam**2))
print(round(V, 3), f'{min(p, 1):.1e}')Angles vs a curve fixed in advance (here uniform), any departure; where 0° sits does not matter, unlike KS. Watson’s U² is its Cramér–von Mises twin.
Two circular samples, shuffled
d = load('homing')
a, b = [np.radians(d.query('site == @s').bearing.to_numpy()) for s in ('north', 'east')]
def gap(a, b): # angle between the two mean directions
m = np.angle(np.exp(1j * a).mean()) - np.angle(np.exp(1j * b).mean())
return abs(np.angle(np.exp(1j * m)))
rng = np.random.default_rng(1)
sim = np.array([gap(*np.split(rng.permutation(np.r_[a, b]), [len(a)])) for _ in range(999)])
print(round(np.degrees(gap(a, b)), 1), round((np.sum(sim >= gap(a, b)) + 1) / 1000, 4))Do two sets of angles point differently? Shuffle the labels: no von Mises curve, no shared κ. Never run a t on degrees: 359° and 1° are 2° apart.
Watson–Williams
d = load('homing')
g = [np.radians(d.query('site == @s').bearing.to_numpy()) for s in ('north', 'east', 'south')]
res = lambda a: np.hypot(np.cos(a).sum(), np.sin(a).sum())
Ri, R, N, k = sum(res(a) for a in g), res(np.concatenate(g)), sum(len(a) for a in g), len(g)
r = Ri / N
kap = -0.4 + 1.39 * r + 0.43 / (1 - r) # κ from R̄, valid for 0.53 ≤ R̄ < 0.85
F = (1 + 3 / (8 * kap)) * (N - k) * (Ri - R) / ((k - 1) * (N - Ri))
print(round(kap, 2), round(F, 3), round(stats.f.sf(F, k - 1, N - k), 4))Circular ANOVA: do k groups share a mean direction? Assumes von Mises data with one shared κ; check R̄ per group. Unequal spreads: Watson U².