Comparing several groups in Python
One-way ANOVA, and the rank-based alternative when variances differ.
import numpy as np
from scipy import stats
rng = np.random.default_rng(3)
python = rng.normal(100, 10, 30)
rust = rng.normal(95, 10, 30)
css = rng.normal(80, 10, 30)
print(round(stats.levene(python, rust, css).pvalue, 4))
anova = stats.f_oneway(python, rust, css)
print(round(anova.statistic, 3), f"{anova.pvalue:.2e}")
pairs = [("py-rust", python, rust), ("py-css", python, css)]
for name, a, b in pairs:
print(name, f"{stats.ttest_ind(a, b).pvalue:.4f}")
How it works
f_onewaytakes one array per group.- A significant F says the groups differ, not which pair.
levenechecks the equal-variance assumption first.
Keywords and builtins used here
asforprintround
The run, in numbers
- Lines
- 16
- Characters to type
- 460
- Tokens
- 162
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 93 seconds.
Step 4 of 4 in Hypothesis tests, step 7 of 23 in Scientific computing with SciPy.