A few days back, I hit a strange testing anomaly while validating an automated reporting pipeline for customer feedback. We collect user ratings on a five-point scale before and after deploying an onboarding update. Because our pilot cohort was intentionally small—seven accounts per treatment arm—I assumed SciPy would evaluate the statistical difference between the two cohorts using an exact permutation routine. After all, the official docstring for the Mann-Whitney rank test explains that setting the method parameter to auto will trigger the exact solver whenever the smaller group contains eight or fewer data points.
Here, both cohorts had exactly seven scores. That easily satisfied the documented sample size threshold.
Yet when our automated pipeline printed the final report, the reported significance level caught my eye. The p-value looked suspiciously identical to an asymptotic z-score rather than the discrete probabilities expected from a small-sample permutation distribution. To understand why, I extracted the raw arrays into a standalone Python REPL and compared the function calls side by side.
from scipy.stats import mannwhitneyu, PermutationMethod
import numpy as np
# Survey feedback scores (1-5) from two independent user cohorts
g1 = np.array([1, 2, 2, 2, 3, 2, 5])
g2 = np.array([2, 4, 5, 5, 5, 5, 5])
# Compare how different calculation modes evaluate identical inputs
res_auto = mannwhitneyu(g1, g2, method='auto')
res_asymp = mannwhitneyu(g1, g2, method='asymptotic')
res_exact = mannwhitneyu(g1, g2, method='exact')
print(f"auto: U = {res_auto.statistic:.2f}, p = {res_auto.pvalue:.5f}")
print(f"asymptotic: U = {res_asymp.statistic:.2f}, p = {res_asymp.pvalue:.5f}")
print(f"exact: U = {res_exact.statistic:.2f}, p = {res_exact.pvalue:.5f}")
auto: U = 7.50, p = 0.02454
asymptotic: U = 7.50, p = 0.02454
exact: U = 7.50, p = 0.03788
The numbers revealed the discrepancy immediately. The auto branch did not compute an exact permutation p-value at all. It yielded 0.02454, matching the asymptotic normal approximation down to its final decimal digit. Meanwhile, forcing the exact flag produced an entirely different figure of 0.03788.
Digging into the SciPy implementation clarifies why this happens. The automatic selector inspects two distinct prerequisites rather than just sample size. First, the size of the smaller cohort cannot exceed eight. Second, and crucially, the combined dataset cannot contain any tied values. If even a single tie appears anywhere across the pooled observations, the auto branch immediately discards the exact solver and routes your calculation through the asymptotic normal approximation. Because discrete Likert responses inevitably contain repeated ratings, every small survey dataset silently triggers this fallback.
Why does the library abandon the exact routine the moment duplicates appear? The reason comes down to algorithmic assumptions. SciPy's underlying combinatorial engine relies on a closed-form recursion designed strictly for continuous variables where the theoretical probability of identical measurements is zero. That algorithm does not know how to partition tied mid-ranks across discrete permutations.
If you attempt to override this behavior by hardcoding the exact flag on tied inputs, the function executes the continuous recursion anyway. It computes permutations as if every observation held a unique rank, ignoring tie corrections altogether. That is why our manual exact run returned 0.03788 instead of the true probability. In short, forcing the exact method on tied arrays does not provide an exact test for ties; it simply provides an uncorrected test.
By contrast, the asymptotic pathway explicitly compensates for duplicated scores. It applies a half-unit continuity adjustment to the numerator and reduces the denominator variance according to the standard tie-sum formula:
Var(U) = (n1 * n2 / 12) * ( (n1 + n2 + 1) - sum(t_i^3 - t_i) / ((n1 + n2) * (n1 + n2 - 1)) )
Here, each t_i represents the size of a tied cluster. In our Likert example, the repeated occurrences of twos and fives compress the ranking variance, yielding U = 7.50 and an asymptotic p-value of 0.02454.
What should you do if your project demands an authentic permutation p-value on small tied data? In current versions of SciPy, you do not need to settle for an unadjusted formula or a continuous approximation. You can supply an explicit permutation object that resamples the observed data while preserving its tie structure:
# Construct an exact or Monte Carlo permutation test that respects ties
perm_cfg = PermutationMethod(n_resamples=9999, random_state=20261123)
res_perm = mannwhitneyu(g1, g2, method=perm_cfg)
print(f"permutation: U = {res_perm.statistic:.2f}, p = {res_perm.pvalue:.5f}")
permutation: U = 7.50, p = 0.02564
This conditional permutation routine evaluates the rank sums across label shuffles while keeping the tied rank structure intact, delivering a reliable empirical p-value.
Beyond p-values, engineers building automated pipelines should also avoid reporting raw statistics in isolation. In our toy benchmark, knowing that U = 7.50 tells stakeholders very little about the magnitude of difference between the cohorts. A standard way to convey practical significance is the rank-biserial correlation, which corresponds directly to Cliff's delta.
The metric represents the share of pairwise wins minus the share of pairwise losses across both groups. You can compute it directly from the smaller group's rank sum:
r_rb = (2.0 * U1) / (n1 * n2) - 1.0
def calc_rank_biserial(u_val, count1, count2):
max_u = count1 * count2
return (2.0 * u_val) / max_u - 1.0
effect = calc_rank_biserial(res_auto.statistic, len(g1), len(g2))
print(f"Rank-biserial effect size: {effect:.4f}")
Rank-biserial effect size: -0.6939
Because the null expectation for U under equal sample sizes is n1 * n2 / 2 = 24.5, obtaining 7.50 produces an effect size of -0.6939. The negative sign confirms that users in our first cohort consistently assigned lower ratings than users in the second cohort.
A final conceptual trap worth noting is the common belief that the Mann-Whitney test functions as a universal comparison of sample medians. In our toy fixture, the first group has a median of 2.0 while the second has a median of 5.0. However, the underlying mathematics tests stochastic dominance—whether values in one group systematically exceed those in the other—not median equality. The test only reflects pure median shifts if both underlying populations possess identical shapes and spreads. When variances or skews diverge, two groups can share the same numerical median while producing a statistically significant rank difference.
When writing data processing pipelines in Python, keep four practical rules in mind. First, remember that auto selects an asymptotic test the moment repeated values appear. Second, never force the exact parameter on discrete or ordinal metrics, as doing so drops tie correction. Third, use PermutationMethod when dealing with small, heavily tied samples that require non-asymptotic evaluation. Finally, always pair the test statistic with an effect size such as the rank-biserial correlation so your reports convey magnitude alongside statistical significance.
Top comments (0)