Mann-Whitney U & Kruskal-Wallis with Dunn's Post-Hoc Test: Nonparametric Guide

When analyzing skewed biomarkers, clinical lengths of stay, or Likert scales, nonparametric rank tests offer robust alternatives to t-tests and ANOVA. Here is how to apply Mann–Whitney U and Kruskal–Wallis with Dunn's post-hoc test without falling into median myths, unadjusted p-value traps, or tie-correction errors.

HumanPen Team

· 13 min read

Mann–Whitney U and Kruskal–Wallis with Dunn's post-hoc test: core rules

To analyze skewed or ordinal outcomes correctly, use the Mann–Whitney U test for two independent groups and Kruskal–Wallis H for three or more groups, followed by Dunn's post-hoc test. Contrary to widespread belief, these tests evaluate stochastic dominance (`P(X > Y) + 0.5 P(X = Y) != 0.5`) rather than differences between medians, testing median equality only when distributions share identical shapes and spreads. When ties exist, avoid SciPy's uncorrected exact method, apply Dunn's pooled-rank post-hoc procedure rather than isolated pairwise Mann–Whitney re-rankings, adjust pairwise p-values with Holm's step-down correction, and report rank effect sizes (`r_rb` or `E^2_R`) alongside medians and interquartile ranges.

Biomedical researchers, epidemiologists, and social scientists frequently turn to rank-based non-parametric tests when continuous biomarkers, hospital lengths of stay, or ordinal survey ratings violate normality. Yet textbooks and software outputs frequently misstate the underlying null hypotheses, leading authors to claim median shifts where none exist or execute flawed post-hoc pipelines that inflate Type I error rates. Aligning your non-parametric workflow with contemporary biostatistical standards connects directly to formatting Table 1 baseline clinical characteristics, analyzing Likert scale survey responses from Excel to APA tables, and learning how to replicate legacy SPSS and Stata analyses in Python and R.

Analytical DimensionMann–Whitney U TestKruskal–Wallis H + Dunn's TestOrdinal Logistic / Permutation Test
Number of GroupsExactly 2 independent groups3 or more independent groups2 or more groups, with covariates
Null Hypothesis TestedStochastic equality: P(X > Y) + 0.5 P(X = Y) = 0.5Stochastic equality across all k group distributionsCommon odds ratio across cutoffs / arbitrary test statistic under label shuffle
Core Distributional AssumptionIndependent observations; median test requires equal shape and spreadIndependent observations; median test requires equal shape and spread across all groupsProportional odds across ordinal score thresholds; exchangeability under permutation
Post-Hoc Pairwise ProcedureNot applicable (single pairwise comparison)Dunn's test using joint pooled ranks and tie-corrected varianceContrasts on model log-odds or pairwise permutation distributions
Standard Effect Size MetricRank-biserial correlation r_rb (numerically identical to Cliff's delta)Rank epsilon-squared E^2_R or rank eta-squared eta^2_HAdjusted cumulative odds ratio (OR) with 95% CI
Software Default Trapauto uses exact only when min(n1, n2) <= 8 and no ties (switching to asymptotic for ties); forcing exact omits tie correctionscikit-posthocs and R dunn.test default to no multiplicity correctionFailure to test proportional odds assumption via Brant test
Mann–Whitney U and Kruskal–Wallis H test stochastic dominance across rank distributions rather than medians; pair Kruskal–Wallis with Dunn's pooled-rank post-hoc test and Holm p-adjustment rather than isolated pairwise re-rankings.

Why Hart (2001) warns against treating Mann–Whitney as a pure median test

In a landmark British Medical Journal paper, Alan Hart (2001, BMJ, PMCID: PMC1120984) cautioned researchers that the Mann–Whitney test is not simply a test of medians, and treating it as such can lead to flawed interpretations of scientific data. The test evaluates the null hypothesis that the distributions of two independent populations are equal against the alternative that one distribution is stochastically greater than the other (`P(X > Y) + 0.5 P(X = Y) != 0.5`). As formalized in survival function notation (`S_X(u) != S_Y(u)` for at least one threshold `u`), the test statistic reflects both location and shape. It functions as a test of population medians only under the restrictive pure location-shift assumption—namely, that the two population distributions possess identical shapes, skews, and dispersions, differing solely by a constant horizontal shift.

When distribution shapes or variances diverge, relying on median comparisons produces striking paradoxes. For example, consider two clinical cohorts evaluating postoperative pain on a visual analog scale: Cohort A exhibits a symmetrical distribution centered at 4.0, while Cohort B exhibits a bimodal or heavily right-skewed distribution also centered at a median of 4.0 but with a long upper tail of severe pain scores. The sample medians for both groups are identical (`4.0 vs 4.0`), yet a two-sided Mann–Whitney test can yield a highly significant result (`p < 0.01`) because observations in Cohort B systematically outrank observations in Cohort A across the upper percentiles. Conversely, if one group has a higher median but much larger dispersion, the test may fail to reach significance or even show stochastic dominance in the unexpected direction.

  • Generate kernel density plots, boxplots, and violin plots to visually inspect whether group distributions share comparable shapes, spreads, and skewness directions.
  • If shapes and spreads are substantially identical, interpret a significant Mann–Whitney or Kruskal–Wallis result as a valid shift in population medians.
  • If shapes or variances diverge substantially, report the test as evidence of stochastic dominance or rank-distribution differences rather than claiming a median shift.
  • When unequal variances coincide with unequal sample sizes, consider the heteroskedasticity-robust Brunner–Munzel test or multivariable proportional odds ordinal logistic regression.
Two independent samples can share identical medians yet yield p < 0.01 on Mann–Whitney U when skewness or variance differs; always report medians alongside interquartile ranges and inspect graphical distributions.

Dunn's post-hoc test, Holm p-adjustment, and software tie-handling traps

When an omnibus Kruskal–Wallis test rejects the null hypothesis of stochastic equality across three or more groups, researchers must conduct pairwise post-hoc comparisons to determine which specific groups differ. A common but methodologically flawed practice is running separate pairwise Mann–Whitney U tests on each pair of groups. As Olive Jean Dunn demonstrated in her foundational paper (Dunn, 1964, Technometrics), separate pairwise Mann–Whitney tests re-rank each pair of samples in isolation, discarding the pooled ranking information from the full sample of size `N` and ignoring the global pooled rank variance. In contrast, Dunn's test preserves the joint mean ranks (`R_bar_i - R_bar_j`) established during the omnibus Kruskal–Wallis test and divides each pairwise rank difference by a standard error derived from the total pooled sample with tie correction, ensuring post-hoc contrasts remain mathematically consistent with the omnibus test.

Statistical software implementations introduce subtle traps in tie handling that catch unwary analysts. In SciPy (`v1.18.0`), `scipy.stats.mannwhitneyu(x, y, method='auto')` selects `method='exact'` only when the smaller group size is at most 8 and the data contain zero tied values. If a researcher manually forces `method='exact'` on tied data—such as ordinal 5-point Likert survey responses or discrete clinical scores—SciPy computes the exact permutation distribution without making any adjustment for ties, generating incorrect p-values. For tied data in small samples, analysts should employ `scipy.stats.PermutationMethod()` for an exact conditional permutation test that respects ties, or use `method='asymptotic'`, which applies both a continuity correction (`1/2`) and an explicit tie-variance adjustment. For multi-group data, `scipy.stats.kruskal` automatically applies the standard tie-corrected formula for the `H` statistic.

A second critical pitfall lies in default multiplicity corrections. Python's `scikit_posthocs.posthoc_dunn(..., p_adjust=None)` and R's `dunn.test::dunn.test(..., method="none")` default to no p-value adjustment, leaving researchers vulnerable to rampant family-wise error rate (FWER) inflation across multiple pairwise comparisons. In contrast, R's `FSA::dunnTest()` defaults to `method="holm"`. Analysts must explicitly specify `p_adjust='holm'` in `scikit-posthocs` or `p_adjust='fdr_bh'` when false discovery rate control is preferred. Holm's step-down procedure tests ordered unadjusted p-values against sequentially adjusted alpha thresholds (`alpha / (m - i + 1)`), making it uniformly more powerful than the traditional Bonferroni correction while providing strong control of the family-wise error rate under arbitrary dependence structures.

Never conduct unadjusted pairwise Mann–Whitney tests after Kruskal–Wallis; execute Dunn's test using joint pooled ranks and explicitly pass p_adjust='holm' to guard against family-wise error rate inflation.

Reporting medians, interquartile ranges, and rank effect sizes (r_rb, E^2_R, eta^2_H)

Reporting non-parametric rank tests in clinical and academic manuscripts requires presenting both descriptive dispersion metrics and standardized non-parametric effect sizes. Because rank tests are deployed precisely when continuous variables depart from normality, reporting sample means and standard deviations (`mean ± SD`) is methodologically inappropriate and distorts skewed clinical reality. Authors should report the sample median alongside the interquartile range (`median [IQR]`), explicitly clarifying in the table footnote whether the bracketed values represent the 25th and 75th percentiles (e.g., `42.0 [28.0, 58.0]`) or the interquartile distance. Connecting non-parametric tables to reproducible scripts ensures direct compatibility when learning how to replicate legacy SPSS and Stata analyses in Python and R.

Standard reporting guidelines under APA 7th edition and ICMJE medical journals require coupling test statistics with standardized effect sizes and their confidence intervals. For the two-sample Mann–Whitney U test, the standard effect size is the rank-biserial correlation `r_rb` (R `effectsize::rank_biserial`, v0.8.9), which is numerically identical to Cliff's delta (`delta`). In terms of the test statistic `U_1` returned by SciPy and R (where `U_1` counts pairwise instances where group 1 exceeds group 2), it is calculated as `r_rb = (2 × U_1) / (n_1 × n_2) - 1`, or equivalently `(U_1 - U_2) / (n_1 × n_2)`. This directly reflects the difference between the proportion of favorable and unfavorable pairs, scaling from -1 (complete stochastic dominance of group 2) to +1 (complete dominance of group 1), with R `effectsize::rank_biserial(x, y)` computing this metric alongside a `95% CI`. For multi-group Kruskal–Wallis tests, analysts should report rank epsilon-squared (`E^2_R = H / (n - 1)`) or rank eta-squared (`eta^2_H = (H - k + 1) / (n - k)`), derived from Tomczak and Tomczak (2014) and implemented in R `effectsize::rank_epsilon_squared`. By convention, `eta^2_H` values of 0.01, 0.06, and 0.14 correspond to small, medium, and large effects.

  • Report exact test statistics, group sample sizes, and degrees of freedom: for Mann–Whitney, state `U`, sample sizes `n_1` and `n_2`, and asymptotic `z` if applicable; for Kruskal–Wallis, state `H`, degrees of freedom `df = k - 1`, and total `n`.
  • Report exact two-sided p-values to three decimal places (e.g., `p = 0.004`), avoiding vague threshold designations such as `p < 0.05` unless `p < 0.001`.
  • Provide standardized rank effect sizes with 95% confidence intervals, reporting `r_rb` for two-group tests and `E^2_R` or `eta^2_H` for multi-group omnibus comparisons.
  • Present post-hoc Dunn pairwise comparisons in a structured summary matrix or three-line table displaying mean rank differences, standard errors, adjusted p-values (`p_adj`), and pairwise rank-biserial correlations.
Complement every U and H statistic with medians, IQRs, and standardized rank effect sizes such as r_rb or rank eta-squared; reporting p-values without effect magnitudes leaves clinical significance unquantified.

Automating non-parametric tables and Dunn post-hoc matrices in HumanPen Start Project

Managing complex non-parametric pipelines—verifying distribution shapes, calculating tie-adjusted rank statistics, constructing Dunn post-hoc comparison matrices with Holm adjustments, and formatting publication-grade Table 1 summaries—can be orchestrated end-to-end within HumanPen Start Project. Attach your data and papers, describe what you need, approve the plan before work starts, and get the reviewed report, charts, and code ready to preview online or download.

This reproducible analysis workflow is demonstrated in the public hotel booking cancellation analysis project live on the platform (explore the hotel booking cancellation public project). Processing raw multi-source reservation datasets across resort and city hotel properties, the platform conducted automated data audits, non-parametric distributional assessments across stay lengths and lead times, leakage-free out-of-time predictive modeling (`ROC-AUC = 0.832`, `PR-AUC = 0.800`), and policy impact simulations. The delivered package comprises a 19-page `.docx` analytical report, a 12-slide `.pptx` briefing deck with speaker notes, an executable `.ipynb` Jupyter notebook, 10 publication figures, 21 structured CSV summary tables, and a unified `results.json` ensuring identical figures across written documents and slides.

Researchers can upload raw datasets, protocols, and reference papers in Excel, CSV, Word, PDF, or zip archives up to 2 GB per project. All data transformations and non-parametric calculations execute within an isolated computing sandbox running Python or R; workflows originally planned in SPSS or Stata are translated into verifiable Python or R code. Data from proprietary restricted databases such as CNKI or Wind must be exported locally before uploading, and GPU training is not supported. Anyone can explore public example projects on the platform without signing in, reviewing delivered report structures, reproducible code pipelines, and publication-ready tables before submitting their own data. Every project runs in an isolated sandbox encrypted in transit, undergoes two-stage plan confirmation, maintains version history across revisions, and is retained for 6 months (180 days) after last activity with a 3-day reminder and anytime manual deletion. All delivered tables, reports, and scripts serve as an audited methodological and learning reference scaffold; investigators remain responsible for verifying data, supplying personal disclosures, and adhering to institutional ethics and journal policies.

Every project executes in an isolated sandbox encrypted in transit, confirms project scope before work commences, preserves version histories across revisions, and provides verified Python and R scripts.

Frequently asked questions

Can I use the Mann–Whitney U test on paired data, such as pre-treatment and post-treatment biomarker measurements? No, the Mann–Whitney U test is strictly designed for two independent groups. When evaluating paired or repeated observations on the same experimental units (such as pre-intervention and post-intervention lab values), you must use the Wilcoxon signed-rank test. The Wilcoxon signed-rank test ranks the absolute differences between paired observations and assigns signs based on the direction of change, testing whether the median difference between paired pairs equals zero under a symmetrical distribution assumption.

Why does scipy.stats.kruskal evaluate the test statistic using a chi-square distribution rather than an exact distribution? The Kruskal–Wallis test statistic `H` asymptotically follows a chi-square distribution with `k - 1` degrees of freedom under the null hypothesis as sample sizes grow. When each group contains at least 5 observations, the continuous chi-square approximation provides excellent precision. When sample sizes are extremely small (e.g., three groups with 3 observations each) and contain tied values, the chi-square approximation can be slightly anti-conservative; in such specialized cases, researchers should compute exact permutation p-values using Monte Carlo sampling.

When should I choose Holm p-adjustment over Benjamini–Hochberg FDR for Dunn's post-hoc comparisons? The choice depends on whether your study is confirmatory or exploratory. Holm's step-down procedure strictly controls the family-wise error rate (FWER), ensuring that the probability of making even a single false-positive claim across all pairwise comparisons remains below alpha (e.g., 0.05). It is mandatory for regulatory trials, confirmatory clinical studies, and primary endpoint evaluations. In contrast, Benjamini–Hochberg controls the false discovery rate (FDR)—the expected proportion of false discoveries among rejected nulls—which provides higher statistical power in exploratory multi-group screening.

What should I report if two groups have identical sample medians but the Mann–Whitney test yields p = 0.003? Do not claim that one group had a significantly higher median than the other, as that statement is contradicted by your descriptive data. Instead, report that the two groups differed significantly in their overall rank distributions (Mann–Whitney `U = 412.0`, `p = 0.003`, rank-biserial correlation `r_rb = 0.38`), reflecting stochastic dominance where observations in one group tended to exceed those in the other. Accompany the test statistic with medians, interquartile ranges (`Q1–Q3`), and a violin or boxplot illustrating the underlying differences in skewness and spread.

Sources and statistical references

Primary methodological literature, statistical formulas, and software package manuals verified via live retrieval on November 22, 2026. Consult target journal guidelines and institutional review protocols for specific non-parametric reporting conventions.

KEEP READING