Skip to content

Which statistical test

A test answers one question: could chance alone explain the difference you see? Four facts pick the test: the outcome type, the number of groups, whether the measurements are paired (the same units measured twice) and whether the assumptions hold. This guide maps those facts to a SciPy or statsmodels function and to the effect size to report next to the p-value. The examples use the checkout A/B test in data/ab_test.csv.

flowchart TD
    A{"Outcome type?"} -->|numeric| B{"How many groups?"}
    A -->|"binary (a rate)"| P{"How many groups?"}
    A -->|"two categoricals"| X["chi2_contingency<br/>fisher_exact if small"]
    A -->|"two numerics"| C["pearsonr / spearmanr"]
    B -->|1| B1["ttest_1samp<br/>or wilcoxon"]
    B -->|2| B2{"Paired?"}
    B2 -->|yes| B3["ttest_rel<br/>or wilcoxon"]
    B2 -->|no| B4["Welch ttest_ind<br/>or mannwhitneyu"]
    B -->|"3+"| B5{"Paired?"}
    B5 -->|yes| B6["AnovaRM<br/>or friedmanchisquare"]
    B5 -->|no| B7["Welch f_oneway, then Games–Howell;<br/>or kruskal, then pairwise<br/>mannwhitneyu + Holm"]
    P -->|1| P1["binomtest"]
    P -->|2| P2{"Paired?"}
    P2 -->|yes| P3["mcnemar"]
    P2 -->|no| P4["proportions_ztest<br/>fisher_exact if small"]
    P -->|"3+"| P5["chi2_contingency"]

In each box, the first test assumes a roughly normal mean (or large samples); the second one (after “or”) uses ranks and suits skewed, ordinal or small data.

I want to… Use… Effect size to report
compare a mean with a target stats.ttest_1samp(x, popmean=m) mean − target, with its CI
compare two independent means stats.ttest_ind(a, b, equal_var=False) (Welch) difference with CI, Cohen’s d
compare two skewed or ordinal groups stats.mannwhitneyu(a, b) rank-biserial r, difference of medians with a bootstrap CI
compare before/after on the same units stats.ttest_rel(after, before) mean difference, dzd_z
compare skewed paired data stats.wilcoxon(after, before) median difference
compare 3+ independent means stats.f_oneway(*groups, equal_var=False) η²
compare 3+ skewed groups stats.kruskal(*groups) ε²
find which pairs differ (means) stats.tukey_hsd(*groups, equal_var=False) (Games–Howell) pairwise differences with CIs
find which pairs differ (ranks) mannwhitneyu per pair + multipletests(p, method="holm") rank-biserial r per pair
compare 3+ conditions on the same units AnovaRM(df, "y", "subject", within=["cond"]).fit() partial η²
the same, with skewed data stats.friedmanchisquare(a, b, c) Kendall’s W
test one rate against a value stats.binomtest(k, n, p=p0) rate − p0, .proportion_ci()
compare two rates proportions_ztest([k1, k2], [n1, n2]) difference in percentage points, relative lift
a CI for a difference of rates confint_proportions_2indep(k1, n1, k2, n2, method="newcomb")
compare two rates with small counts stats.fisher_exact(table) odds ratio
compare paired yes/no outcomes mcnemar(table, exact=True) discordant pairs
test two categorical variables stats.chi2_contingency(pd.crosstab(a, b)) Cramér’s V
test counts against expected shares stats.chisquare(obs, f_exp=expected_counts)
a linear relation of two numbers stats.pearsonr(x, y) r with .confidence_interval()
a monotonic relation, outliers, ranks stats.spearmanr(x, y), stats.kendalltau(x, y) ρ, τ
any difference between two distributions stats.ks_2samp(a, b) the KS statistic
a p-value for any statistic stats.permutation_test((a, b), stat, rng=rng) the statistic itself
a CI for any statistic stats.bootstrap((x,), np.median, rng=rng)
control for other variables smf.ols("y ~ group + x", df), smf.logit(...) the coefficient with its CI
check normality stats.probplot(x) (Q-Q plot)
check equal variances stats.levene(a, b)
adjust many p-values stats.false_discovery_control(p), multipletests(p, method="holm")
plan the sample size NormalIndPower().solve_power(effect_size=h, power=0.8)

Imports: from scipy import stats; from statsmodels.stats.proportion import proportions_ztest, confint_proportions_2indep; from statsmodels.stats.contingency_tables import mcnemar; from statsmodels.stats.anova import AnovaRM; from statsmodels.stats.power import NormalIndPower; from statsmodels.stats.proportion import proportion_effectsize; from statsmodels.stats.multitest import multipletests; import statsmodels.formula.api as smf.

Outcome Groups Paired Data Test Function Effect size
numeric 1 — mean roughly normal one-sample t ttest_1samp(x, popmean=m) (xˉ−m)/s(\bar x - m)/s
numeric 1 — skewed Wilcoxon signed-rank wilcoxon(x - m) median − m
numeric 2 no means, any variances Welch t ttest_ind(a, b, equal_var=False) aˉ−bˉ\bar a - \bar b with CI; Cohen’s d
numeric 2 no skewed, ordinal, outliers Mann–Whitney U mannwhitneyu(a, b) rank-biserial 2U/(n1n2)−12U/(n_1 n_2) - 1
numeric 2 no unequal spreads, ranks Brunner–Munzel brunnermunzel(a, b) P(A>B)P(A > B)
numeric 2 yes differences roughly normal paired t ttest_rel(after, before) dz=dˉ/sdd_z = \bar d / s_d
numeric 2 yes skewed differences Wilcoxon signed-rank wilcoxon(after, before) median difference
numeric 3+ no means one-way ANOVA (Welch) f_oneway(*g, equal_var=False) η² = SS_between / SS_total
numeric 3+ no skewed Kruskal–Wallis kruskal(*g) ε² = H / (n − 1)
numeric 3+ no all pairs of means, unequal variances Games–Howell tukey_hsd(*g, equal_var=False) pairwise differences with CIs
numeric 3+ no all pairs of means, similar SDs Tukey HSD tukey_hsd(*g) pairwise differences with CIs
numeric 3+ no all pairs after Kruskal–Wallis pairwise Mann–Whitney + Holm mannwhitneyu per pair, multipletests(p, method="holm") rank-biserial r per pair
numeric 3+ yes balanced, normal-ish repeated-measures ANOVA AnovaRM(...).fit() partial η²
numeric 3+ yes skewed Friedman friedmanchisquare(a, b, c) Kendall’s W
binary 1 — k successes of n exact binomial binomtest(k, n, p=p0) p^−p0\hat p - p_0 with CI
binary 2 no every cell ≥ 5 expected two-proportion z proportions_ztest([k1, k2], [n1, n2]) p^1−p^2\hat p_1 - \hat p_2, relative lift, Cohen’s h
binary 2 no small counts Fisher exact fisher_exact(table) odds ratio
binary 2 yes the same units twice McNemar mcnemar(table, exact=True) difference of discordant shares
binary or categorical 2+ no every cell ≥ 5 expected chi-square independence chi2_contingency(table) Cramér’s V
counts 1 — observed vs expected shares chi-square goodness of fit chisquare(obs, f_exp=exp) —
two numerics — — linear, no big outliers Pearson pearsonr(x, y) r
two numerics — — monotonic, ordinal, outliers Spearman, Kendall spearmanr(x, y), kendalltau(x, y) ρ, τ
numeric 2 no any shape difference Kolmogorov–Smirnov ks_2samp(a, b) D
anything 2+ either no formula fits permutation test permutation_test(data, stat) your statistic
anything — — other variables matter regression smf.ols, smf.logit coefficient with CI

The two-proportion z-test and chi2_contingency(table, correction=False) on the same 2×2 table give the same p-value: χ2=z2\chi^2 = z^2.

Assumption Used by Check If it fails
independent observations every test above the design: one row per unit, random assignment aggregate to one value per unit, or use a mixed model; test by cluster
the mean is roughly normal t-tests, ANOVA Q-Q plot of each group (stats.probplot); n ≥ 30 per group usually suffices unless the data are very skewed rank test, bootstrap, permutation test, or a log transform
equal variances Student t, classic ANOVA, Tukey HSD stats.levene(a, b), compare the SDs Welch versions: equal_var=False (use them by default)
similar shapes Mann–Whitney, Kruskal as tests of medians histograms or ECDFs read them as “one group tends to be larger”, or use Brunner–Munzel
expected counts ≥ 5 chi-square, z-test for rates chi2_contingency(t).expected_freq fisher_exact, barnard_exact, merge sparse categories
continuous data KS test many ties mean it is not a chi-square test on bins
a linear relation Pearson, OLS scatter plot, residual plot Spearman, a transform, a flexible model

Do not use a significant Shapiro–Wilk test as a gate. With thousands of rows, it rejects harmless departures. With 10 rows, it misses large ones. Read the Q-Q plot.

A p-value says whether an effect is distinguishable from noise. An effect size says how large it is. Report both, with a confidence interval.

Effect size Formula or code Rough scale
difference of means ttest_ind(...).confidence_interval() in the data’s units: the most useful
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 of rates p^1−p^2\hat p_1 - \hat p_2, confint_proportions_2indep percentage points
relative lift (p^1−p^2)/p^2(\hat p_1 - \hat p_2)/\hat p_2 business context
relative risk stats.contingency.relative_risk(k1, n1, k2, n2) 1 = no effect
odds ratio stats.contingency.odds_ratio(table) 1 = no effect
Cohen’s h proportion_effectsize(p1, p2) input for power analysis
rank-biserial r 2U/(n1n2)−12U/(n_1 n_2) - 1 −1 to 1; 0 = no tendency
r, ρ pearsonr, spearmanr 0.1 small, 0.3 medium, 0.5 large
Cramér’s V stats.contingency.association(table) 0.1 weak, 0.3 moderate (2 columns)
η², ε² between-group SS / total SS; H / (n − 1) share of variance explained
import numpy as np
import pandas as pd
from scipy import stats
from statsmodels.stats.proportion import confint_proportions_2indep, proportions_ztest
ab = pd.read_csv("data/ab_test.csv")
t = ab[ab["group"] == "treatment"]
c = ab[ab["group"] == "control"]
rng = np.random.default_rng(42)

Binary outcome, two independent groups, thousands of users per group → two-proportion z-test. Report the difference with its CI:

k = [int(t["converted"].sum()), int(c["converted"].sum())]
n = [len(t), len(c)]
z, p = proportions_ztest(k, n)
low, high = confint_proportions_2indep(k[0], n[0], k[1], n[1], method="newcomb")
print(f"treatment {k[0] / n[0]:.2%}, control {k[1] / n[1]:.2%}, p = {p:.4f}")
print(f"difference: 95% CI [{low:.2%}, {high:.2%}]")
Output
treatment 11.66%, control 10.12%, p = 0.0129
difference: 95% CI [0.33%, 2.77%]

Numeric outcome, two independent groups, large n, some skew → Welch t-test, with Mann–Whitney as a robustness check. Cohen’s d sizes the effect:

a, b = t["time_on_page_s"].to_numpy(), c["time_on_page_s"].to_numpy()
res = stats.ttest_ind(a, b, equal_var=False)
pooled = np.sqrt((a.var(ddof=1) + b.var(ddof=1)) / 2) # equal-n approximation
print(f"skew {stats.skew(a):.2f}, Welch p = {res.pvalue:.1e}")
print(f"difference CI {np.round(res.confidence_interval(), 1)} s")
print(f"d = {(a.mean() - b.mean()) / pooled:.2f}, Mann-Whitney p = "
f"{stats.mannwhitneyu(a, b).pvalue:.1e}")
Output
skew 1.27, Welch p = 2.5e-17
difference CI [ 6.9 11.1] s
d = 0.17, Mann-Whitney p = 4.1e-20

A tiny p-value with d = 0.17 means a small effect that is clearly real. Whether 9 more seconds matter is a business question, not a statistical one.

Revenue of buyers is skewed (a few large orders) → Mann–Whitney for the test, a bootstrap CI for the difference of medians:

tr = t.loc[t["converted"] == 1, "revenue"].to_numpy()
cr = c.loc[c["converted"] == 1, "revenue"].to_numpy()
def median_diff(x, y, axis):
return np.median(x, axis=axis) - np.median(y, axis=axis)
ci = stats.bootstrap((tr, cr), median_diff, n_resamples=2000, rng=rng)
mw = stats.mannwhitneyu(tr, cr)
print(f"skew {stats.skew(tr):.1f}, Mann-Whitney p = {mw.pvalue:.3f}")
print(f"median difference CI [{ci.confidence_interval.low:.2f}, "
f"{ci.confidence_interval.high:.2f}]")
Output
skew 2.4, Mann-Whitney p = 0.282
median difference CI [-5.40, 2.06]

The CI includes 0: no evidence that the value of an order changed. This compares buyers only, and the treatment changes who buys (more conversions). For the effect of the treatment on money, compare revenue per user over all users, zeros included:

rev_t, rev_c = t["revenue"].to_numpy(), c["revenue"].to_numpy()
res_rev = stats.ttest_ind(rev_t, rev_c, equal_var=False) # n is large: CLT
print(f"revenue per user {rev_t.mean():.2f} vs {rev_c.mean():.2f}, "
f"p = {res_rev.pvalue:.3f}, CI {np.round(res_rev.confidence_interval(), 2)}")
Output
revenue per user 4.85 vs 4.38, p = 0.157, CI [-0.18 1.11]

Revenue per user is 0.47 higher in the treatment group, but the CI includes 0: the test cannot yet show a revenue effect.

“Which devices differ in time on page?”

Section titled ““Which devices differ in time on page?””

Three groups → an omnibus test, then a pairwise follow-up that matches it. After Welch ANOVA, use Games–Howell (tukey_hsd with equal_var=False). After Kruskal–Wallis, use pairwise Mann–Whitney tests with a Holm correction. Tukey HSD controls the family-wise error rate itself, so it does not need a significant omnibus test first:

from itertools import combinations
from statsmodels.stats.multitest import multipletests
devices = sorted(ab["device"].unique())
groups = [ab.loc[ab["device"] == d, "time_on_page_s"].to_numpy() for d in devices]
print(devices, "SDs", [round(float(g.std(ddof=1)), 1) for g in groups])
print(f"Welch ANOVA p = {stats.f_oneway(*groups, equal_var=False).pvalue:.1e}")
gh = stats.tukey_hsd(*groups, equal_var=False) # Games-Howell
pairs = list(combinations(range(len(devices)), 2))
raw = [stats.mannwhitneyu(groups[i], groups[j]).pvalue for i, j in pairs]
holm = multipletests(raw, method="holm")[1]
for (i, j), p_holm in zip(pairs, holm, strict=True):
print(f"{devices[i]:>7} vs {devices[j]:<7} Games-Howell p = {gh.pvalue[i, j]:.3f}"
f" Mann-Whitney + Holm p = {p_holm:.3f}")
Output
['desktop', 'mobile', 'tablet'] SDs [53.9, 51.9, 55.3]
Welch ANOVA p = 3.5e-40
desktop vs mobile Games-Howell p = 0.000 Mann-Whitney + Holm p = 0.000
desktop vs tablet Games-Howell p = 0.000 Mann-Whitney + Holm p = 0.000
mobile vs tablet Games-Howell p = 0.642 Mann-Whitney + Holm p = 0.884

Both follow-ups agree: desktop differs from mobile and tablet; mobile and tablet do not differ. Here the SDs are similar, so plain tukey_hsd(*groups) would give almost the same answer.

“Does conversion depend on the device?”

Section titled ““Does conversion depend on the device?””

Two categorical variables (3 devices × converted) → chi-square test of independence and Cramér’s V:

table = pd.crosstab(ab["device"], ab["converted"])
chi = stats.chi2_contingency(table)
print(table)
print(f"p = {chi.pvalue:.1e}, min expected = {chi.expected_freq.min():.0f}, "
f"V = {stats.contingency.association(table):.3f}")
Output
converted 0 1
device
desktop 2974 454
mobile 5061 516
tablet 876 119
p = 1.4e-08, min expected = 108, V = 0.060

The minimum expected count is far above 5, so the test is valid. V ≈ 0.06 is a weak association: the dependence is real but small.

Paired numeric data → test the differences. An unpaired test on the same numbers loses the pairing and most of its power:

before = np.array([31.0, 28.5, 40.2, 35.1, 22.8, 30.4, 27.9, 33.6])
after = np.array([29.2, 27.9, 37.5, 34.0, 22.1, 28.3, 27.5, 31.4])
print(f"paired t p = {stats.ttest_rel(after, before).pvalue:.4f}")
print(f"Wilcoxon p = {stats.wilcoxon(after, before).pvalue:.4f}")
print(f"unpaired p = {stats.ttest_ind(after, before).pvalue:.4f} (wrong test)")
Output
paired t p = 0.0020
Wilcoxon p = 0.0078
unpaired p = 0.5665 (wrong test)

“Did the treatment work in each country?”

Section titled ““Did the treatment work in each country?””

Seven tests at α = 0.05 → expect false positives. Adjust the p-values with Benjamini–Hochberg (false discovery rate):

pvals = {}
for country, g in ab.groupby("country"):
table = pd.crosstab(g["group"], g["converted"])
pvals[country] = stats.chi2_contingency(table, correction=False).pvalue
raw = pd.Series(pvals)
result = pd.DataFrame({"p": raw, "p_bh": stats.false_discovery_control(raw)})
print(result.round(3).sort_values("p"))
Output
p p_bh
CA 0.025 0.176
FR 0.068 0.237
DE 0.120 0.280
US 0.209 0.340
AU 0.243 0.340
UK 0.516 0.603
IN 0.707 0.707

Canada looks significant alone (p ≈ 0.025) but not after the adjustment. Decide on subgroup tests before you see the data, and report them as exploratory.

Trap Symptom Fix
Student t (ttest_ind default) with unequal variances wrong p-values equal_var=False (Welch) always
tukey_hsd(*g) after Kruskal–Wallis or Welch ANOVA a follow-up that assumes equal variances and normal means Games–Howell (equal_var=False), or pairwise mannwhitneyu + Holm
an unpaired test on paired data a large p-value; the effect is missed ttest_rel or wilcoxon on the pairs
many rows per user treated as independent p-values far too small one value per user, or a mixed model
a normality test as a gate big n: always “not normal”; small n: never read a Q-Q plot; think about the CLT
Mann–Whitney read as a test of medians wrong claims when shapes differ “group A tends to be larger”; bootstrap the median difference
chi-square with expected counts below 5 an unreliable p-value fisher_exact, barnard_exact, or merge categories
chi2_contingency on a 2×2 table vs a z-test the p-values differ Yates’ correction; correction=False matches the z-test
chisquare with shares as f_exp ValueError: the sums differ expected counts: shares * obs.sum()
a significant p-value read as a big effect a 0.1-point change “proven” with a million rows report the effect size and its CI
“p > 0.05, so no effect” an underpowered test read as proof report the CI; plan power in advance
testing many metrics or segments false discoveries pick one primary metric; adjust with BH or Holm
peeking at a running A/B test the false-positive rate grows far above α fix n in advance, or use a sequential design
a one-sided test chosen after seeing the data a p-value half as large, but invalid decide the direction before collecting data
“observed power” after a test it is only a restatement of the p-value do power analysis before the test
a correlation read as causation confounders explain the link an experiment, or adjust in a regression
alternative="greater" the direction looks reversed it means first argument > second argument
NaN in the input the result is nan nan_policy="omit" or dropna()