Pulse Data Hub

T-Test vs Mann-Whitney U Test in Python, with Real Data

The t-test vs Mann-Whitney question comes up whenever you compare two groups: do you test means with a t-test, or ranks with the Mann-Whitney U test? Textbooks say “use Mann-Whitney when the data is not normal”, but the two tests answer different questions, and on real data they sometimes disagree. Below we run both in Python on two real datasets, add effect sizes, and use a simulation to see what each test actually detects.

Versions: pandas 3.0.5 and SciPy 1.18.1. Data are the seaborn penguins (333 complete rows) and Titanic files. If you want the testing basics first, see A/B test significance in Python.

Case 1: roughly normal data (penguin flippers)

Compare flipper length for Adelie (146 birds) and Chinstrap (68 birds) penguins. Both groups pass a Shapiro-Wilk normality check (p = 0.743 and 0.811).

import pandas as pd, numpy as np
from scipy import stats

pg = pd.read_csv("penguins.csv").dropna()
a = pg[pg.species == "Adelie"].flipper_length_mm
c = pg[pg.species == "Chinstrap"].flipper_length_mm
print(len(a), len(c), a.mean().round(2), c.mean().round(2))
print(stats.ttest_ind(a, c, equal_var=False))
print(stats.mannwhitneyu(a, c, alternative="two-sided"))

Output:

146 68 190.1 195.82
TtestResult(statistic=-5.611506646889242, pvalue=1.296588862863426e-07, df=120.88083335236657)
MannwhitneyuResult(statistic=2691.5, pvalue=6.851376281411792e-08)

Both tests agree: Chinstrap flippers are about 5.7 mm longer on average, with p-values near 1e-7. When data is close to normal, the two tests give the same verdict, and the t-test is the more familiar one. Use equal_var=False (Welch) by default; it does not require equal spreads.

Case 2: skewed data (Titanic fares)

Fares are strongly right-skewed. Women paid more on average than men in this file.

t = pd.read_csv("titanic.csv")
f = t[t.sex == "female"].fare
m = t[t.sex == "male"].fare
print(len(f), len(m), "mean", f.mean().round(2), m.mean().round(2),
      "median", f.median(), m.median())
print("skew", stats.skew(f).round(2), stats.skew(m).round(2))
print(stats.ttest_ind(f, m, equal_var=False))
print(stats.mannwhitneyu(f, m, alternative="two-sided"))

Output:

314 577 mean 44.48 25.52 median 23.0 10.5 skew 3.26 6.6
TtestResult(statistic=5.077499013458909, pvalue=5.388057409693924e-07, df=504.9643005334164)
MannwhitneyuResult(statistic=119003.0, pvalue=9.61232696290926e-15)
Bar chart of Titanic fares: mean 44.48 for women and 25.52 for men, median 23.00 and 10.50
The mean is dragged up by a few very large fares; the median gap is a better summary of a typical passenger.

Both reject the null hypothesis, but the p-values differ by almost eight orders of magnitude, and neither number says how big the difference is. That is the job of an effect size.

Effect sizes: Cohen’s d and probability of superiority

Mann-Whitney’s statistic U divided by n1 times n2 is the probability that a random woman’s fare exceeds a random man’s (ties count half). It is more interpretable than a p-value.

def cohens_d(x, y):
    sp = np.sqrt(((len(x)-1)*x.var() + (len(y)-1)*y.var()) / (len(x)+len(y)-2))
    return (x.mean() - y.mean()) / sp

U = stats.mannwhitneyu(f, m).statistic
ps = U / (len(f) * len(m))
print("Cohen d", round(cohens_d(f, m), 3), "P(superiority)", round(ps, 3),
      "rank-biserial", round(2*ps - 1, 3))

Output:

Cohen d 0.388 prob superiority 0.657 rank-biserial 0.314

A random woman paid more than a random man 65.7% of the time. That is a modest effect, which fits the small Cohen’s d of 0.39. A bootstrap (5,000 resamples, seed 0) puts the median difference of 12.5 at a 95% interval of 7.5 to 15.5. A permutation test on the mean difference (10,000 shuffles) gave p = 0.0001, the smallest value it can report with that many shuffles, which agrees with both tests above.

What each test actually tests

The t-test compares means. Mann-Whitney tests whether one group tends to produce larger values than the other, which equals a difference in medians only when the two distributions have the same shape. A simulation shows the difference. Two lognormal groups of 40 with the same median (1.0) but different spread (sigma 1.0 vs 1.5) have different means. Over 5,000 runs:

r = np.random.default_rng(1); n = 5000; rej_t = rej_mw = 0
for _ in range(n):
    x = r.lognormal(0, 1.0, 40); y = r.lognormal(0, 1.5, 40)
    rej_t  += stats.ttest_ind(x, y, equal_var=False).pvalue < .05
    rej_mw += stats.mannwhitneyu(x, y).pvalue < .05
print("Welch rejects", rej_t/n, "MW rejects", rej_mw/n)

Output:

Welch rejects 0.1466 MW rejects 0.0512

Welch rejected 14.7% of the time because the means really differ; Mann-Whitney rejected 5.1%, close to the 5% you expect when the medians are equal. Neither is wrong; they answer different questions. If the question is about total spend or revenue, means matter. If it is about a typical customer, ranks or medians fit better. On equal lognormal groups of 20, the false-positive rates were 3.9% for the t-test and 4.5% for Mann-Whitney, so both stay close to nominal at small sample sizes.

More than two groups

For three penguin species (146, 68 and 119 birds) the counterparts are one-way ANOVA (F = 341.9, p = 3.7e-81) and Kruskal-Wallis (H = 212.1, p = 8.8e-47). As with two groups, the verdicts agree here. Related reading: outlier detection helps decide whether a few extreme fares are driving a mean, and correlation vs causation reminds us that a significant difference is not an explanation.

A simple decision guide

Pick the test that matches your question, report an effect size and an interval, and check the plot. Documentation: scipy.stats.mannwhitneyu and scipy.stats.ttest_ind.

Frequently asked questions

Is Mann-Whitney a non-parametric t-test?

It is a rank-based alternative, but it does not test the same hypothesis. It tests whether one group tends to be larger, not whether the means are equal.

When should I use Welch’s t-test instead of Student’s?

Almost always. Welch’s version handles unequal variances and loses little power when variances are equal.

Does a big sample make the normality assumption irrelevant?

The t-test is fairly robust with large samples, but heavy skew and outliers still make the mean a poor summary, so look at medians and effect sizes too.

Which effect size should I report with Mann-Whitney?

The probability of superiority (or the rank-biserial correlation, 2 x PS – 1) plus the median difference with a bootstrap interval.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights