How to test variance homogeneity with the Levene test in SciPy (with Code)
The Short Answer (TL;DR)
Call scipy.stats.levene with center="median" to compare the spreads of independent groups using median-centered absolute deviations. Report the statistic and approximate F-reference p-value alongside the group sizes and sampling assumptions.
from scipy import stats
groups = ([9.6,10.1,10.2,9.9,10.4,9.8,10.0,10.3], [8,9,10,11,12,7,13,9], [9.2,10.4,10.8,9.6,11.0,9.8,10.2,9.0])
print(stats.levene(*groups, center="median", nan_policy="raise"))
Detailed Implementation
This example uses synthetic data and does not need a network connection. Install the recorded package versions in a separate Python environment before running it.
python -m pip install numpy==2.5.4 scipy==1.18.1
from pathlib import Path
import numpy as np
from scipy import stats
# Three independent synthetic groups measured in the same units.
groups = [
np.array([9.6,10.1,10.2,9.9,10.4,9.8,10.0,10.3]),
np.array([8,9,10,11,12,7,13,9], dtype=float),
np.array([9.2,10.4,10.8,9.6,11.0,9.8,10.2,9.0]),
]
if len(groups) < 2 or any(g.ndim != 1 or g.size < 2 for g in groups):
raise ValueError("Use at least two independent one-dimensional groups with two values each.")
if any(not np.isfinite(g).all() for g in groups):
raise ValueError("Resolve non-finite measurements before comparing spreads.")
result = stats.levene(*groups, center="median", nan_policy="raise")
if not np.isfinite(result.statistic) or not np.isfinite(result.pvalue):
raise ValueError("Degenerate absolute deviations do not support this F-reference calculation.")
k = len(groups)
n_total = sum(g.size for g in groups)
report = (
f"Group sizes: {[g.size for g in groups]}\n"
f"Group medians: {[float(np.median(g)) for g in groups]}\n"
f"Sample variances (ddof=1): {[float(np.var(g, ddof=1)) for g in groups]}\n"
f"Center: median (Brown-Forsythe version)\n"
f"Levene W: {result.statistic:.8f}\n"
f"Reference degrees of freedom: ({k-1}, {n_total-k})\n"
f"Approximate upper-tail F p-value: {result.pvalue:.8g}\n"
)
print(report)
Path("levene-variance-output.txt").write_text(report, encoding="utf-8")
The report shows group sizes [8, 8, 8], medians [10.05, 9.5, 10.0], W approximately 9.11845625 and approximate p approximately 0.0014109347. The displayed sample variances are about 0.07125, 4.125 and 0.52571429 in squared measurement units. Shifting individual groups or applying one common nonzero scale does not change the test result.
Why specify the median center?
The original mean-centered test and the median-centered Brown-Forsythe version transform observations differently. Here each observation becomes its absolute distance from its own group median. Specifying center="median" makes that choice explicit when results are reproduced. It offers useful resistance to some non-normal data, but does not remove sampling assumptions or guarantee robustness to every form of contamination.
Which groups and measurements are suitable?
Use measurements in common units from independent groups, with independent units within each group. Group lengths may differ even though this example uses eight observations in every group. Repeated measurements, clustered observations and survey weights need methods that account for their design. Inspect the raw observations and group distributions; materially different shapes can affect how a comparison of spread should be interpreted.
Does the result prove equal or unequal variances?
A small p-value is evidence against equal population variances under the test conditions; it does not identify which pair differs or establish a causal mechanism. A large p-value is insufficient evidence against equality, not proof that variances are equal or practically equivalent. Report estimated spreads and sample sizes. Avoid automatically choosing a mean-comparison method from a preliminary variance-test threshold alone.
How accurate is the reference probability?
The usual probability uses an approximate F reference distribution for the transformed observations. Small samples, unusual shapes or dependence can make that approximation poor. The synthetic numbers illustrate the calculation, not evidence that eight observations per group always provide reliable inference. A design-appropriate resampling analysis may be useful when this reference approximation is unsuitable.
Mathematical Context
For group g, form z_gi as the absolute difference between observation i and that group median. Let zbar_g be the mean of those absolute deviations and zbar be their overall mean, weighted by group sizes. Divide the between-group sum n_g times (zbar_g-zbar) squared by the within-group sum (z_gi-zbar_g) squared, then multiply by (N-k)/(k-1). The result is the ordinary one-way ANOVA statistic applied to these absolute deviations. For k=3 and N=24, W is approximately 9.11845625 and the reference degrees of freedom are two and twenty-one. The F upper-tail probability is approximately 0.0014109347. The validation reconstructs both sums independently and also uses the closed-form F survival probability (21/(21+2W)) raised to the power 21/2, which applies here because the numerator degrees of freedom equal two.
\[ z_{gi}=|x_{gi}-\operatorname{median}(x_g)|,\qquad W=\frac{(N-k)\sum_g n_g(\bar{z}_g-\bar{z})^2}{(k-1)\sum_g\sum_i(z_{gi}-\bar{z}_g)^2} \]
Reproducibility
Executed with Python 3.12.14; numpy 2.5.4, scipy 1.18.1. Automated checks confirm the stated output properties.
Primary documentation
- SciPy Levene test and median-centered option
- NIST definition, transformed observations and reference degrees of freedom
- SciPy F survival probability