Club.noww.in
To run a Mann-Whitney U test in Python, pass your two independent samples to scipy.stats.mannwhitneyu(). It returns the U statistic and a p-value telling you whether one group tends to have larger values:
from scipy.stats import mannwhitneyu result = mannwhitneyu(group_a, group_b, alternative="two-sided")My examples use Python 3.12.5 and SciPy 1.18.1, with order values from a Chicago store that tested a new checkout layout.
We’ll run the test, compute U by hand from ranks, add an effect size, try one-sided and exact versions, use pandas groups, and draw a box plot.
When should you use the Mann-Whitney U test?
- You’re comparing two independent groups (different customers, not the same ones twice).
- The data is skewed or has outliers, so a t-test’s normality assumption is shaky.
- The values are at least ordinal, like ratings, times or dollar amounts.
- For paired data, use the Wilcoxon signed-rank test (scipy.stats.wilcoxon) instead.
Order values are a classic case: most are small, and a few big orders ($88.00 and $120.00 here) would drag a mean around.
Mann-Whitney U test in Python with SciPy
Put the samples in lists or arrays and call the function. I’m testing whether the two layouts differ in either direction:
# order values (USD) from two checkout layouts at a Chicago store old_layout = [23.50, 31.20, 18.75, 42.10, 27.80, 19.99, 35.40, 22.15, 29.60, 25.30, 88.00, 21.40] new_layout = [34.90, 41.25, 29.99, 52.60, 38.10, 45.75, 31.80, 120.00, 36.45, 47.20, 33.15, 39.70] from scipy.stats import mannwhitneyu result = mannwhitneyu(new_layout, old_layout, alternative="two-sided") print(f"U = {result.statistic:.1f}, p-value = {result.pvalue:.5f}") print("significant at 0.05" if result.pvalue < 0.05 else "not significant at 0.05")Output:
U = 120.0, p-value = 0.00610 significant at 0.05
U = 120.0 out of a possible 144, and the p-value of 0.0061 is well under 0.05.A p-value below 0.05 means a difference this big would be unlikely if the layouts made no difference. For a refresher on spread, see standard deviation in Python.
How is the Mann-Whitney U statistic calculated?
The test ranks all values together, then adds up the ranks for one group. Doing it by hand confirms what SciPy reports:
# order values (USD) from two checkout layouts at a Chicago store old_layout = [23.50, 31.20, 18.75, 42.10, 27.80, 19.99, 35.40, 22.15, 29.60, 25.30, 88.00, 21.40] new_layout = [34.90, 41.25, 29.99, 52.60, 38.10, 45.75, 31.80, 120.00, 36.45, 47.20, 33.15, 39.70] from scipy.stats import rankdata, mannwhitneyu ranks = rankdata(new_layout + old_layout) # rank all 24 values together n1, n2 = len(new_layout), len(old_layout) r1 = ranks[:n1].sum() # rank sum of the first sample u1 = r1 - n1 * (n1 + 1) / 2 u2 = n1 * n2 - u1 print(f"rank sum R1 = {r1:.1f}") print(f"U1 = {u1:.1f}, U2 = {u2:.1f}, U1 + U2 = n1*n2 = {u1 + u2:.0f}") print("SciPy U:", mannwhitneyu(new_layout, old_layout).statistic) r = 2 * u1 / (n1 * n2) - 1 # rank-biserial correlation print(f"rank-biserial effect size r = {r:.3f}")Output:
rank sum R1 = 198.0 U1 = 120.0, U2 = 24.0, U1 + U2 = n1*n2 = 144 SciPy U: 120.0 rank-biserial effect size r = 0.667
The hand-computed U1 matches SciPy exactly, and U1 + U2 always equals n1 × n2 = 144.SciPy reports U for the first sample you pass. The rank-biserial correlation turns U into an effect size from −1 to 1; 0.667 here means new-layout orders are usually bigger.
One-sided tests and exact p-values
If you only care whether the new layout increases order values, use alternative="greater". You can also pick the exact or normal-approximation method:
# order values (USD) from two checkout layouts at a Chicago store old_layout = [23.50, 31.20, 18.75, 42.10, 27.80, 19.99, 35.40, 22.15, 29.60, 25.30, 88.00, 21.40] new_layout = [34.90, 41.25, 29.99, 52.60, 38.10, 45.75, 31.80, 120.00, 36.45, 47.20, 33.15, 39.70] from scipy.stats import mannwhitneyu for alt in ["two-sided", "greater", "less"]: res = mannwhitneyu(new_layout, old_layout, alternative=alt) print(f"{alt:<10} p = {res.pvalue:.5f}") exact = mannwhitneyu(new_layout, old_layout, alternative="greater", method="exact") approx = mannwhitneyu(new_layout, old_layout, alternative="greater", method="asymptotic") print(f"exact p = {exact.pvalue:.6f} | asymptotic p = {approx.pvalue:.6f}")Output:
two-sided p = 0.00610 greater p = 0.00305 less p = 0.99745 exact p = 0.002257 | asymptotic p = 0.003049
“greater” halves the two-sided p-value; “less” is near 1 because the data points the other way.With method="auto", SciPy chooses the exact distribution for small samples without ties and the normal approximation otherwise, so you rarely need to set it.
Mann-Whitney U test with pandas groups
Real data usually sits in a DataFrame with a group column. Split it with groupby, then pass each group to the test:
# order values (USD) from two checkout layouts at a Chicago store old_layout = [23.50, 31.20, 18.75, 42.10, 27.80, 19.99, 35.40, 22.15, 29.60, 25.30, 88.00, 21.40] new_layout = [34.90, 41.25, 29.99, 52.60, 38.10, 45.75, 31.80, 120.00, 36.45, 47.20, 33.15, 39.70] import pandas as pd from scipy.stats import mannwhitneyu df = pd.DataFrame({"layout": ["old"] * 12 + ["new"] * 12, "order_usd": old_layout + new_layout}) print(df.groupby("layout")["order_usd"].agg(["count", "median", "mean"]).round(2)) groups = dict(tuple(df.groupby("layout")["order_usd"])) res = mannwhitneyu(groups["new"], groups["old"]) print(f"\nMann-Whitney U = {res.statistic:.0f}, p = {res.pvalue:.5f}")Output:
count median mean layout new 12 38.90 45.91 old 12 26.55 32.10 Mann-Whitney U = 120, p = 0.00610Medians tell this story better than means because of the outliers. More pandas tricks in loc vs iloc in pandas.
Plot the two groups with a box plot
A box plot is the natural picture for this test, since both look at medians and spread rather than means:
# order values (USD) from two checkout layouts at a Chicago store old_layout = [23.50, 31.20, 18.75, 42.10, 27.80, 19.99, 35.40, 22.15, 29.60, 25.30, 88.00, 21.40] new_layout = [34.90, 41.25, 29.99, 52.60, 38.10, 45.75, 31.80, 120.00, 36.45, 47.20, 33.15, 39.70] import matplotlib.pyplot as plt plt.figure(figsize=(7, 4.5)) plt.boxplot([old_layout, new_layout], tick_labels=["Old layout", "New layout"]) plt.ylabel("Order value (USD)") plt.title("Order values by checkout layout (Mann-Whitney U, p < 0.01)") plt.tight_layout() plt.show()
The new layout’s box sits higher, and each group has one large outlier.Mann-Whitney U vs t-test
| Compares | Ranks (tends to be larger) | Means |
| Assumes normal data | No | Yes (roughly) |
| Sensitive to outliers | Low | High |
| SciPy function | mannwhitneyu | ttest_ind |
These data analysis guides go well with this test:
- Multiple linear regression in Python
- PCA in Python
- Monte Carlo simulation in Python
- Merge and join in pandas
Frequently asked questions
How do I do a Mann-Whitney U test in Python?
Use scipy.stats.mannwhitneyu(x, y). It returns the U statistic for x and a p-value.
What does the U statistic mean?
It counts how often a value from the first group beats a value from the second, out of n1 × n2 pairs, with ties counting half.
Is Mann-Whitney the same as Wilcoxon rank-sum?
Yes, they’re equivalent tests. The Wilcoxon signed-rank test is different and is for paired data.
Should I use a one-sided or two-sided test?
Two-sided unless you decided the direction before seeing the data. Set it with alternative=.
Does Mann-Whitney compare medians?
Not exactly. It tests whether one group tends to have larger values; it reflects medians only when the shapes are similar.
Where is mannwhitneyu documented?
See scipy.stats.mannwhitneyu in the SciPy docs.












English (US)