Skip to main content
v2026.11,986 entries · CC-BY 4.0

Mann-Whitney U Test in Python: Step-by-Step SciPy Guide

Master the Mann-Whitney U test in Python with SciPy. Learn step-by-step syntax, output interpretation, ties handling, and effect size calculations.

Written and maintained by CASRAI Editorial Board

Published

On this page

The Mann-Whitney U test in Python is a non-parametric statistical hypothesis test executed with the scipy.stats.mannwhitneyu function to evaluate whether two independent groups differ significantly when continuous or ordinal data violate normality assumptions. In academic research and data science, analysts rely on the mann whitney u test python implementation to compare sample distributions without requiring homoscedasticity or normal bell-curve distributions. The test assigns collective ranks across both groups, computes the sum of ranks, and determines the probability that a randomly drawn observation from one population exceeds an observation from the second population.

What SciPy is used for in research

SciPy is a fundamental open-source Python library used across scientific disciplines for mathematics, engineering, and advanced statistical analysis. Within the scipy.stats module, researchers access an extensive suite of probability distributions, summary statistics, and hypothesis testing routines. When comparing two groups, researchers traditionally turn to the independent two-sample Student t-test; however, the t-test relies strictly on the assumption that underlying populations are normally distributed and measured on continuous interval or ratio scales. When studying ordinal endpoints such as Likert scale survey responses, clinical severity scores, or heavily skewed biomarkers, the Student t-test loses statistical validity and statistical power.

The Mann-Whitney U test serves as the primary non-parametric alternative to the independent two-sample t-test. While parametric tests compare population means, the Mann-Whitney U test assesses stochastic equality between two independent groups. Specifically, the null hypothesis states that the distribution of population X is identical to the distribution of population Y. If an investigator assumes that both population distributions share an identical shape and variance, the test functions as a comparison of population medians; however, as demonstrated in statistical literature, without the equal-shape assumption, the test evaluates whether observations from one population stochastically dominate those of the other.

In institutional research settings, executing the mann-whitney u test in python through SciPy provides key methodological advantages:

  • Distribution-free robustness: The rank transformation eliminates distortions caused by extreme outliers or heavy-tailed distributions.
  • Ordinal scale validity: Evaluates rank orders directly without imposing artificial metric assumptions on ranked data.
  • Reproducible computation: Standardizes exact and asymptotic probability calculations within Python data science workflows alongside NumPy and Pandas.

For paired or repeated-measures experimental designs where the same subjects are measured before and after an intervention, researchers must not use the independent Mann-Whitney U test. Instead, paired comparisons require the Wilcoxon signed-rank test. To review the mathematical foundations of distribution-free inference, explore our comprehensive guide to nonparametric statistics, or examine the theoretical framework in Mann-Whitney U test assumptions. For related paired procedures, consult our walkthrough on Wilcoxon signed-rank test assumptions and reporting.

How to install or access SciPy

To use SciPy for statistical computing, researchers install the library from official distribution channels. SciPy requires an active Python environment (Python 3.10 or newer) along with NumPy. In professional data workflows, installing packages within an isolated virtual environment prevents dependency conflicts across separate research projects.

To establish a clean virtual environment and install SciPy using the standard Python package installer (pip), run the following terminal commands:

python3 -m venv research_env
source research_env/bin/activate
pip install --upgrade pip
pip install scipy numpy pandas

For research teams utilizing the Conda package management ecosystem across high-performance computing clusters or local workstations, install SciPy from the community-maintained Conda-Forge channel:

conda create -n stats_env python=3.11
conda activate stats_env
conda install -c conda-forge scipy numpy pandas

Once installation finishes, verify that SciPy is installed correctly and check the active library version by executing a one-line command in your terminal:

python -c "import scipy, numpy; print('SciPy version:', scipy.__version__, '| NumPy version:', numpy.__version__)"

SciPy version 1.9.0 and later versions feature updated array handling, enhanced asymptotic tie corrections, and explicit parameter options for permutation testing, making modern releases essential for rigorous scientific reporting. In addition to core SciPy, scientific practitioners frequently install Pandas for data frame management and specialized packages like Statsmodels and Pingouin to expand their analytical capabilities. For an overview of broader statistical routines available in the library, refer to our detailed tutorial on SciPy stats.

How to perform the Mann-Whitney U test in Python step by step

Performing the mann-whitney u test in python involves preparing independent data arrays, defining hypothesis parameters, selecting the exact or asymptotic calculation algorithm, and extracting the resulting test statistics. Follow these six sequential steps to execute the analysis accurately.

  1. Import the necessary analytical modules: Load the mannwhitneyu function from scipy.stats, along with numpy and pandas for data structure handling:
    import numpy as np
    import pandas as pd
    from scipy.stats import mannwhitneyu, PermutationMethod
  2. Format independent data samples: Ensure that data are structured into two distinct 1D array-like collections. Samples do not need to contain equal numbers of observations, but they must represent independent experimental units. Consider an experimental study evaluating blood pressure reduction scores (mm Hg) between a novel drug group (n1 = 9) and an active control group (n2 = 8):
    drug_group = [14.2, 16.5, 12.8, 18.1, 15.0, 17.4, 19.2, 13.5, 16.8]
    control_group = [11.0, 13.2, 10.5, 14.8, 12.1, 13.9, 11.8, 12.5]

    When working with structured datasets in Pandas, isolate groups using column filtering:

    df = pd.DataFrame({
        "reduction": drug_group + control_group,
        "treatment": ["Drug"] * len(drug_group) + ["Control"] * len(control_group)
    })
    sample_x = df.loc[df["treatment"] == "Drug", "reduction"]
    sample_y = df.loc[df["treatment"] == "Control", "reduction"]
  3. Configure the hypothesis test direction: Set the alternative argument based on your pre-registered study design:
    • alternative='two-sided' (default): Tests whether the distribution of sample x differs stochastically from sample y in either direction.
    • alternative='greater': Tests whether the distribution of sample x is stochastically greater than sample y (stochastically shifted toward higher values).
    • alternative='less': Tests whether the distribution of sample x is stochastically less than sample y.
  4. Select the calculation method and continuity correction: Configure how the p-value is computed using the method parameter:
    • method='auto': SciPy defaults to computing an exact combinatorial p-value if the smaller sample size has 8 or fewer observations and there are no tied values. If ties exist or sample sizes exceed 8, it defaults to the asymptotic normal approximation.
    • method='exact': Forces exact combinatorial calculation under the null distribution. Note that SciPy exact mode does not correct for ties.
    • method='asymptotic': Uses the standardized normal approximation (z-test), incorporating full variance adjustments for tied values. When using asymptotic calculation, use_continuity=True (the default) applies a 0.5 continuity correction to account for approximating a discrete rank distribution with a continuous Gaussian curve.
    • method=PermutationMethod(n_resamples=9999, random_state=42): For small sample sizes containing extensive tied ranks, instantiating a Monte Carlo permutation test provides an exact, tie-robust empirical p-value.
  5. Execute mannwhitneyu and extract output: Call the function and store the returned MannwhitneyuResult container:
    result = mannwhitneyu(
        sample_x,
        sample_y,
        alternative="two-sided",
        method="auto"
    )
    print("U statistic:", result.statistic)
    print("p-value:", result.pvalue)

    For the blood pressure dataset above, running this command yields statistic = 66.0 and exact pvalue = 0.00247.

  6. Calculate non-parametric effect sizes: Because p-values indicate only statistical significance rather than practical magnitude, researchers report standardized effect sizes. The two most widely reported effect sizes are the Common Language Effect Size (CLES) and the Rank-Biserial Correlation (r_rb):
    n1 = len(sample_x)
    n2 = len(sample_y)
    u1 = result.statistic
    
    cles = u1 / (n1 * n2)
    r_rb = (2 * u1) / (n1 * n2) - 1
    
    print(f"CLES (Probability of Superiority): {cles:.3f}")
    print(f"Rank-Biserial Correlation (r_rb): {r_rb:.3f}")

    For our clinical sample, CLES = 66.0 / (9 * 8) = 0.917, meaning there is a 91.7% probability that a patient receiving the drug experiences greater blood pressure reduction than a randomly selected control patient. The corresponding rank-biserial correlation is r_rb = 0.833, demonstrating a large positive effect.

How to read the output

The scipy.stats.mannwhitneyu function returns a specialized MannwhitneyuResult object containing two primary attributes: statistic and pvalue. Understanding what each value represents ensures accurate scientific interpretation and avoids common reporting discrepancies.

The statistic attribute represents the Mann-Whitney U value associated with the first sample passed to the function (sample x). Formally, U1 measures the total number of pairwise comparisons in which an observation from sample x exceeds an observation from sample y, with ties contributing 0.5. The theoretical minimum of U is 0 (complete non-overlap, where every score in y exceeds every score in x), and the theoretical maximum is n1 × n2 (where every score in x exceeds every score in y).

The complementary statistic corresponding to the second sample (U2) can be calculated directly:

u2 = n1 * n2 - u1

A frequent source of confusion among researchers transitioning between software platforms is that SPSS reports the smaller of the two statistics (min(U1, U2)), whereas SciPy and R consistently report U1 corresponding to the first argument. Both formulations produce identical two-sided p-values and lead to identical statistical decisions. For cross-software comparison, see our guide on the Mann-Whitney U test in SPSS.

The relationship between the Mann-Whitney U statistic and the Wilcoxon rank sum (R1) is defined by the linear transformation:

R1 = U1 + (n1 * (n1 + 1)) / 2

When the sample size is moderate or large (typically n1, n2 ≥ 10), the distribution of U converges toward normality under the null hypothesis. The mean (μ_U) and standard error (σ_U) of the null distribution without ties are given by:

  • Mean: μ_U = (n1 × n2) / 2
  • Variance without ties: Var(U) = (n1 × n2 × (n1 + n2 + 1)) / 12
  • Standard error: σ_U = √(Var(U))

When tied values exist, SciPy adjusts the variance formula using tie groupings t_i (the count of observations sharing rank i):

Var_tied(U) = (n1 * n2 / 12) * ((n1 + n2 + 1) - sum(t_i**3 - t_i) / ((n1 + n2) * (n1 + n2 - 1)))

The standardized z-statistic is computed by subtracting the null mean, applying the continuity correction d = 0.5 toward the mean, and dividing by the standard error:

z = (u1 - (n1 * n2 / 2) - 0.5) / sigma_u

To report results according to the American Psychological Association (APA 7th edition) guidelines, state the medians and interquartile ranges (IQR) for both groups, followed by the U statistic, the standardized z-score, the exact p-value, and the effect size metric:

“A Mann-Whitney U test revealed a statistically significant difference in blood pressure reduction between the novel drug group (Mdn = 16.5 mm Hg, IQR = 3.2) and the control group (Mdn = 12.3 mm Hg, IQR = 1.8), U = 66.0, z = 2.84, p = .002, r_rb = .83.”

Troubleshooting SciPy

When executing the mann whitney u test python routine in complex research pipelines, analysts encounter predictable edge cases. Review these five troubleshooting scenarios to diagnose and resolve calculation errors.

1. Asymmetric U statistics caused by argument order: Reversing the input arguments changes the reported U statistic. For example, mannwhitneyu(x, y) returns U1, whereas mannwhitneyu(y, x) returns U2 = n1 × n2 – U1. While a two-sided test produces the exact same p-value regardless of argument order, one-sided directional hypotheses (alternative='greater' or 'less') will invert their findings if arguments are swapped. Always verify that sample x corresponds to the intended experimental focal group.

2. Unhandled missing values producing NaN outputs: By default, SciPy sets nan_policy='propagate'. If either sample vector contains a single missing value (np.nan), the function silently returns MannwhitneyuResult(statistic=nan, pvalue=nan). To resolve this without manual array slicing, set nan_policy='omit' to automatically drop missing observations, or pass pre-cleaned series using df['score'].dropna().

3. Small sample ties distorting exact p-values: When sample sizes are small (such as n1, n2 fewer than 10 observations) and the data contain repeated numbers (ties), choosing method='exact' executes a combinatorial algorithm that assumes continuous, untied data. SciPy does not correct for ties in exact mode and raises no warning, which can lead to conservative or inaccurate p-values. In the presence of ties in small datasets, use a permutation test by supplying method=PermutationMethod(n_resamples=9999, random_state=42), or allow method='asymptotic' to apply tie-corrected variance.

4. Inappropriate use on paired observations: A frequent methodological mistake is applying mannwhitneyu to pre-test and post-test measurements from the same research participants. The Mann-Whitney U test requires strictly independent observations. Violating the independence assumption inflates standard errors and misestimates Type I error rates. Paired comparisons must be analyzed using scipy.stats.wilcoxon.

5. Misinterpreting the test as a pure median comparison: If the dispersion, skewness, or overall shapes of the two group distributions differ markedly, the Mann-Whitney U test can produce a statistically significant p-value even when both population medians are identical. In such scenarios, the test correctly detects stochastic dominance (one group’s values systematically ranking higher), not a median shift. When reporting findings, plot violin plots or empirical cumulative distribution functions alongside median figures to confirm whether distribution shapes are homogeneous.

Free alternatives to SciPy

While SciPy is the standard foundational engine for scientific Python computing, several free and open-source alternatives offer streamlined syntax, automatic effect size calculation, or graphical user interfaces. The table below outlines key capabilities across popular tools:

Software / Package Primary Function / Command Built-in Effect Sizes Tie Handling User Interface
SciPy scipy.stats.mannwhitneyu Manual calculation required Variance correction in asymptotic mode Python programmatic API
Pingouin pingouin.mwu RBC (Rank-Biserial) and CLES Automatic tie adjustment Pandas-centric Python API
Statsmodels rank_compare_2indep Probability of superiority with 95% CI Variance adjustment for ties Python statistical modeling API
R (stats) wilcox.test(x, y, paired=FALSE) Available via external libraries (rcompanion) Exact unadjusted, asymptotic adjusted R command line / scripts
Jamovi Independent Samples T-Test (Mann-Whitney) Rank-biserial correlation Standard tie correction Desktop graphical interface

Among Python alternatives, Pingouin stands out for behavioral and biomedical scientists because calling pingouin.mwu(x, y) returns a clean Pandas DataFrame containing the U statistic, asymptotic p-value, rank-biserial correlation, and common language effect size in a single execution. Statsmodels provides rigorous econometric formulations, including asymptotic confidence intervals for stochastic dominance. For non-programmers, open-source desktop suites such as Jamovi and JASP wrap R statistical engines in intuitive spreadsheet interfaces, generating publication-ready tables without writing code.

For an in-depth reference matrix comparing default parameters, exact methods, and licensing terms across these libraries, consult the data table below.

Frequently asked questions

How do you perform a Mann-Whitney U test in Python?

To perform a Mann-Whitney U test in Python, import the mannwhitneyu function from the scipy.stats library. Pass your two independent numeric samples as array-like arguments: statistic, p_value = mannwhitneyu(sample_x, sample_y, alternative='two-sided'). The function computes the U statistic for the first group and returns the corresponding p-value.

What library is used for the Mann-Whitney U test in Python?

SciPy (specifically the scipy.stats module) is the primary scientific library used for the Mann-Whitney U test in Python. Other popular Python libraries supporting this analysis include Pingouin, which outputs automatic effect sizes, and Statsmodels, which provides confidence intervals for rank comparisons.

What are the parameters for scipy.stats.mannwhitneyu?

The main parameters for scipy.stats.mannwhitneyu are x and y (the two independent sample arrays), use_continuity (a boolean defaulting to True that applies a 0.5 continuity adjustment in asymptotic mode), alternative (options: ‘two-sided’, ‘less’, or ‘greater’), axis (the array dimension along which to compute), method (‘auto’, ‘exact’, ‘asymptotic’, or a PermutationMethod instance), and nan_policy (‘propagate’, ‘omit’, or ‘raise’).

When should you use a Mann-Whitney U test instead of a t-test?

You should use a Mann-Whitney U test instead of an independent two-sample t-test when your data violate the assumption of normality, when sample sizes are small and skewed, or when outcomes are measured on ordinal scales such as Likert survey ratings. It provides valid hypothesis testing without requiring continuous, normally distributed variables.

How do you interpret the output of mannwhitneyu?

The output of mannwhitneyu contains the test statistic (U) and the p-value. The U statistic reflects the number of times scores in the first sample outrank scores in the second sample. If the p-value is below your predetermined significance threshold (typically α = 0.05), you reject the null hypothesis of equal distributions, concluding that one group stochastically dominates the other.

Sources

Data: Mann-Whitney U Test Implementations Across Statistical Software Libraries

Comprehensive comparison of parameter configurations, default p-value calculation methods, tie-correction algorithms, and built-in effect size metrics across Python and open-source statistical computing libraries, compiled from official software documentation in November 2026.

Period covered: 2026. Coverage: Global.

Mann-Whitney U Test Implementations Across Statistical Software Libraries
Software PackageDefault Calculation MethodTie Handling ProcedureContinuity CorrectionBuilt-in Effect SizesSoftware License
SciPy mannwhitneyuAuto (exact for nVariance correction in asymptotic mode; uncorrected in exact modeTrue (0.5 continuity adjustment)None (manual calculation required)BSD-3-Clause
Pingouin mwuAsymptotic (standard normal approximation)Automatic tie correction in variance calculationTrue (enabled by default)Rank-biserial correlation (RBC) and Common Language Effect Size (CLES)GPL-3.0
Statsmodels rank_compare_2indepAsymptotic normal approximation or Monte Carlo permutationAdjusts asymptotic variance for tied observationsFalse (standard normal without continuity)Probability of superiority with confidence intervalsBSD-3-Clause
R stats wilcox.testAuto (exact for nUncorrected in exact mode; corrected in normal approximationTrue (continuity correction enabled by default)None (available via rcompanion or effectsize packages)GPL-2.0 or GPL-3.0

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Mann-Whitney U Test in Python: Step-by-Step SciPy Guide

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →