SciPy More Hypothesis Tests
The Statistical Significance Tests lesson covered t-tests, normality checks and rank tests for one or two groups. This lesson adds the tests you need for more than two groups, for categorical data (counts), and two modern, assumption-light approaches: permutation tests and the bootstrap.
| Question | Test |
|---|---|
| Do 3+ group means differ? | f_oneway (one-way ANOVA) |
| Which pairs differ after ANOVA? | tukey_hsd |
| Do 3+ groups differ (non-normal data)? | kruskal |
| Do groups have equal variances? | levene, bartlett |
| Do observed counts match expected ones? | chisquare |
| Are two categorical variables related? | chi2_contingency, fisher_exact |
| Any statistic, no distribution assumptions | permutation_test, bootstrap |
One-way ANOVA
Three fertilisers are each tried on eight plots. Are the average yields different? ANOVA compares the variation between groups with the variation within groups:
import numpy as np
from scipy import stats
a = np.array([20.1, 21.4, 19.8, 22.0, 20.7, 21.1, 20.3, 21.8])
b = np.array([22.5, 23.1, 21.9, 24.0, 22.8, 23.4, 22.2, 23.6])
c = np.array([20.9, 21.7, 20.2, 22.4, 21.0, 21.9, 20.8, 22.1])
res = stats.f_oneway(a, b, c)
print(f"F = {res.statistic:.3f}, p = {res.pvalue:.2e}")
print("group means:", [round(float(g.mean()), 3) for g in (a, b, c)])
print("equal variances? Levene p =", round(stats.levene(a, b, c).pvalue, 4))F = 15.606, p = 7.03e-05
group means: [20.9, 22.938, 21.375]
equal variances? Levene p = 0.871
A small p-value says at least one mean differs, but not which. A post-hoc test such as Tukey's HSD compares every pair while controlling the overall error rate:
import numpy as np
from scipy import stats
a = np.array([20.1, 21.4, 19.8, 22.0, 20.7, 21.1, 20.3, 21.8])
b = np.array([22.5, 23.1, 21.9, 24.0, 22.8, 23.4, 22.2, 23.6])
c = np.array([20.9, 21.7, 20.2, 22.4, 21.0, 21.9, 20.8, 22.1])
res = stats.tukey_hsd(a, b, c)
names = "ABC"
for i in range(3):
for j in range(i + 1, 3):
print(f"{names[i]} vs {names[j]}: diff = {res.statistic[i, j]:6.3f}, p = {res.pvalue[i, j]:.4f}")A vs B: diff = -2.038, p = 0.0001
A vs C: diff = -0.475, p = 0.4411
B vs C: diff = 1.562, p = 0.0014
Fertiliser B differs from both others; A and C are indistinguishable.
Chi-square tests for counts
A die is rolled 120 times. If it is fair, each face should come up about 20 times. chisquare() tests observed counts against expected ones:
from scipy import stats
observed = [18, 22, 16, 25, 14, 25]
res = stats.chisquare(observed) # expected: equal counts
print(f"chi2 = {res.statistic:.2f}, p = {res.pvalue:.4f}")
loaded = [10, 12, 11, 14, 13, 60]
print(f"loaded die p = {stats.chisquare(loaded).pvalue:.2e}")chi2 = 5.50, p = 0.3579
loaded die p = 2.89e-19
To check whether two categorical variables are related, put their counts in a contingency table and use chi2_contingency(). Here: does the preferred drink depend on age group?
import numpy as np
from scipy import stats
# coffee tea juice
table = np.array([[45, 20, 35], # under 30
[60, 35, 15]]) # 30 and over
res = stats.chi2_contingency(table)
print(f"chi2 = {res.statistic:.3f}, dof = {res.dof}, p = {res.pvalue:.4f}")
print("expected counts if unrelated:")
print(np.round(res.expected_freq, 1))chi2 = 13.789, dof = 2, p = 0.0010
expected counts if unrelated:
[[50. 26.2 23.8]
[55. 28.8 26.2]]
For small 2 × 2 tables (expected counts below about 5), use fisher_exact() instead.
Permutation tests
A permutation test asks: if the group labels didn't matter, how often would shuffling them produce a difference as large as the one we saw? It works for any statistic and makes no assumption about the distribution:
import numpy as np
from scipy import stats
control = np.array([12.1, 14.3, 11.8, 13.5, 12.9, 13.0, 12.4])
treated = np.array([14.8, 15.2, 13.9, 16.1, 14.4, 15.7, 14.9])
def mean_diff(x, y, axis):
return np.mean(x, axis=axis) - np.mean(y, axis=axis)
res = stats.permutation_test((treated, control), mean_diff, vectorized=True,
n_resamples=9999, random_state=np.random.default_rng(0))
print(f"observed difference = {res.statistic:.3f}")
print(f"permutation p-value = {res.pvalue:.4f}")observed difference = 2.143
permutation p-value = 0.0012
Bootstrap confidence intervals
The bootstrap resamples your data with replacement thousands of times to estimate how much a statistic would vary from sample to sample. It gives a confidence interval for almost anything — here, the median:
import numpy as np
from scipy import stats
rng = np.random.default_rng(8)
delivery_days = rng.gamma(shape=2, scale=1.5, size=50)
res = stats.bootstrap((delivery_days,), np.median, n_resamples=2000,
confidence_level=0.95, random_state=np.random.default_rng(1))
ci = res.confidence_interval
print(f"sample median: {np.median(delivery_days):.3f} days")
print(f"95% CI : ({ci.low:.3f}, {ci.high:.3f})")
print(f"std error : {res.standard_error:.3f}")sample median: 2.459 days
95% CI : (1.779, 3.941)
std error : 0.481
Note: Running many tests on the same data inflates the chance of a false positive. With 20 independent tests at α = 0.05 you'd expect one "significant" result by luck alone. Use a post-hoc procedure (like Tukey's HSD) or adjust p-values with
stats.false_discovery_control().
Test yourself
ANOVA gives p = 0.001 for four groups. What can you conclude?
- All four means differ from each other
- At least one group mean differs; a post-hoc test shows which
- The variances are equal
- Group 1 is the largest
Which test checks whether two categorical variables are related, using a table of counts?
- ttest_ind
- chi2_contingency
- pearsonr
- f_oneway
What does a bootstrap do?
- Fits a normal distribution
- Resamples the data with replacement to estimate the variability of a statistic
- Shuffles group labels to test a hypothesis
- Removes outliers