Skip to main content

Data analysis · Intermediate · 28 min

Test whether two groups really differ: t-test, Mann-Whitney and chi-square

By Padding · Updated 18 Nov 2026
Python 3.15 · NumPy 2.5.5 · SciPy 1.18.1 (checked on python:3.15-slim)

You will pick and run the right SciPy test for means, skewed times, ratings, counts and before-and-after data, and report each result as an effect size with a confidence interval, not a bare p-value.

On this page

Two numbers are never exactly equal. Machine A's bags weigh a little more than machine B's, one courier is a few minutes quicker, a new sign-up screen converts slightly better. The question a test answers is narrower than most people think: if there were no real difference, how surprising would a gap this big be? That answer, the p-value, tells you nothing about how big the difference is or whether it matters. So in this tutorial every test you run sits next to an effect size and a confidence interval.

The hard part is usually not running the test but choosing it. The data decides:

  • Two sets of roughly bell-shaped measurements (weights, scores): Welch's t-test on the means.
  • Skewed times or ordered ratings (delivery minutes, 1 to 5 stars): Mann-Whitney U, which works on ranks.
  • Counts of yes and no (signed up or not): chi-square test, or Fisher's exact test when the counts are small.
  • The same people measured twice (before and after a course): a paired t-test or the Wilcoxon signed-rank test.

You generate one seeded dataset for each case, run the test that fits it, see what goes wrong with the test that does not, and finish with a script that writes every result as a sentence a manager can read.

Step 1 · Create the project and install SciPy

Make a throwaway folder and a virtual environment, and install NumPy and SciPy at the versions this tutorial was written against:

Bash
mkdir -p ~/group-tests-demo
cd ~/group-tests-demo
python3 -m venv .venv
. .venv/bin/activate
pip install "numpy==2.5.5" "scipy==1.18.1"
python -c "import numpy, scipy; print(numpy.__version__, scipy.__version__)"

The data is random but seeded, so you get the same numbers as this page only with the same NumPy version; a later version may draw some distributions differently. The SciPy wheel is several tens of megabytes. If you are on prepaid mobile data, install it once over Wi-Fi: pip caches the download, and a second project on the same machine reuses it.

Check it worked

The last command prints 2.5.5 1.18.1, and your prompt starts with (.venv). In a new terminal, run cd ~/group-tests-demo and . .venv/bin/activate again before the later steps.

Step 2 · Generate the five datasets

Put every dataset in one module, data.py. Each function makes its own generator with its own seed, so changing one dataset never shifts the numbers in another.

Bash
cd ~/group-tests-demo
cat > data.py <<'PY'
"""Generated datasets for comparing two groups. Each function uses its own seed."""
import numpy as np


def bag_weights():
    """Weights in grams of 500 g rice bags from two packing machines."""
    rng = np.random.default_rng(101)
    machine_a = rng.normal(502.0, 4.0, size=40)
    machine_b = rng.normal(499.5, 7.0, size=60)
    return machine_a.round(1), machine_b.round(1)


def delivery_minutes():
    """Delivery times in minutes for two couriers: most are quick, a few are very slow."""
    rng = np.random.default_rng(202)
    courier_a = rng.lognormal(np.log(35), 0.5, size=80)
    courier_b = rng.lognormal(np.log(42), 0.5, size=80)
    return courier_a.round(1), courier_b.round(1)


def ratings():
    """Ratings from 1 (poor) to 5 (excellent) for the same two couriers."""
    rng = np.random.default_rng(303)
    courier_a = rng.choice([1, 2, 3, 4, 5], size=80, p=[0.05, 0.10, 0.25, 0.35, 0.25])
    courier_b = rng.choice([1, 2, 3, 4, 5], size=80, p=[0.10, 0.20, 0.30, 0.25, 0.15])
    return courier_a, courier_b


def signups():
    """Visitors and sign-ups for two versions of an onboarding screen."""
    rng = np.random.default_rng(404)
    visitors_a, visitors_b = 1200, 1180
    signed_a = rng.binomial(visitors_a, 0.13)
    signed_b = rng.binomial(visitors_b, 0.16)
    return np.array([[signed_a, visitors_a - signed_a],
                     [signed_b, visitors_b - signed_b]])


def typing_speed():
    """Words per minute for the same 30 staff before and after a typing course."""
    rng = np.random.default_rng(505)
    before = rng.normal(38, 9, size=30)
    after = before + rng.normal(2.5, 3.0, size=30)
    return before.round(1), after.round(1)
PY
. .venv/bin/activate
python -c "import data; a, b = data.bag_weights(); c, d = data.delivery_minutes(); before, after = data.typing_speed(); print(a.size, b.size, c.size, d.size, before.size); print(data.signups())"

Because you wrote the generators, you know the truth behind each dataset: machine A really does fill bags about 2.5 g heavier, courier B really is slower, screen B really converts better, and the course really helps. A real analysis never has that luxury, which is why it is worth seeing whether each test finds a difference you know is there.

Name your scripts after what they analyse, not after a library. A file called typing.py, statistics.py or random.py in this folder hides the standard library module of the same name, and an import that needs it (NumPy's, for typing.py) can fail with a confusing error.

Check it worked

The command prints the group sizes and the sign-up table, with sign-ups in the first column and non-sign-ups in the second:

Text
40 60 80 80 30
[[ 157 1043]
 [ 186  994]]

Step 3 · Compare two means with Welch's t-test

Bag weights are measurements that cluster around a target, so comparing means is reasonable. The two machines differ in more than their average, though: machine B is less consistent, and you have 60 of its bags against 40 of A's. Student's t-test, the textbook version, assumes both groups have the same spread. Welch's t-test does not, and costs almost nothing when the spreads happen to be equal, so make it your default.

SciPy's ttest_ind runs Student's test unless you pass equal_var=False:

Bash
cd ~/group-tests-demo
. .venv/bin/activate
cat > weights.py <<'PY'
import numpy as np
from scipy import stats

import data

a, b = data.bag_weights()
print(f"machine A: n={a.size}, mean {a.mean():.2f} g, sd {a.std(ddof=1):.2f} g")
print(f"machine B: n={b.size}, mean {b.mean():.2f} g, sd {b.std(ddof=1):.2f} g")

welch = stats.ttest_ind(a, b, equal_var=False)
low, high = welch.confidence_interval(confidence_level=0.95)
diff = a.mean() - b.mean()
pooled_sd = np.sqrt((a.var(ddof=1) + b.var(ddof=1)) / 2)
print(f"Welch t = {welch.statistic:.2f}, df = {welch.df:.1f}, p = {welch.pvalue:.4f}")
print(f"difference A - B: {diff:.2f} g, 95% CI {low:.2f} to {high:.2f} g")
print(f"effect size (Cohen's d): {diff / pooled_sd:.2f}")

student = stats.ttest_ind(a, b)
print(f"for comparison, Student's t (equal variances assumed): df = {student.df:.0f}, p = {student.pvalue:.4f}")
PY
python weights.py

Read the output from the bottom of the decision up:

  • The interval is the answer. Machine A's bags are between 0.74 g and 5.68 g heavier, with 3.21 g the best single estimate. Whether that matters is a business question: at the top of the range, A gives away about 1% extra rice per bag.
  • Cohen's d is the gap divided by a typical spread. About 0.5 means the two sets of weights overlap a lot; a single bag tells you little about which machine filled it.
  • The p-value of 0.0115 says that a gap of 3.2 g or more would be unusual if the machines were really alike. It does not say there is a 1% chance the machines are alike.
  • Student's test gives a different p-value from the same data, because it pretends both machines are equally consistent. With unequal spreads and unequal group sizes, it can be wrong in either direction.

Check it worked

You see machine B's larger standard deviation and these lines:

Text
Welch t = 2.58, df = 91.1, p = 0.0115
difference A - B: 3.21 g, 95% CI 0.74 to 5.68 g
effect size (Cohen's d): 0.49
for comparison, Student's t (equal variances assumed): df = 98, p = 0.0250

Welch's degrees of freedom (91.1) are not a whole number; that is how you can tell which test a report used.

Step 4 · Compare skewed times and ratings with Mann-Whitney U

Delivery times have a floor (nothing arrives in zero minutes) and a long tail of very late orders. One 147-minute delivery can drag a mean around, so comparing means answers a question nobody asked. Mann-Whitney U ranks all the times from both couriers together and asks whether one courier's deliveries tend to sit higher in the ranking.

Its natural effect size comes straight from U: divide by the number of possible A-and-B pairs and you get the chance that a randomly picked A delivery is slower than a randomly picked B delivery. Pair it with a bootstrap interval for the difference in medians, which you can say in minutes:

Bash
cd ~/group-tests-demo
. .venv/bin/activate
cat > deliveries.py <<'PY'
import numpy as np
from scipy import stats

import data

a, b = data.delivery_minutes()
for name, x in (("courier A", a), ("courier B", b)):
    print(f"{name}: median {np.median(x):.1f} min, mean {x.mean():.1f} min, "
          f"slowest {x.max():.0f} min, skew {stats.skew(x):.2f}")

mw = stats.mannwhitneyu(a, b, alternative="two-sided")
superiority = mw.statistic / (a.size * b.size)
print(f"Mann-Whitney U = {mw.statistic:.0f}, p = {mw.pvalue:.4f}")
print(f"chance a random A delivery is slower than a random B delivery: {superiority:.2f}")
print(f"rank-biserial correlation: {2 * superiority - 1:.2f}")


def median_gap(x, y, axis=-1):
    return np.median(x, axis=axis) - np.median(y, axis=axis)


boot = stats.bootstrap((a, b), median_gap, n_resamples=9999,
                       confidence_level=0.95, rng=np.random.default_rng(1))
low, high = boot.confidence_interval
print(f"median A - median B: {median_gap(a, b):.1f} min, 95% bootstrap CI {low:.1f} to {high:.1f} min")
PY
python deliveries.py

stats.bootstrap resamples each courier's deliveries with replacement 9,999 times and recomputes the median gap each time. The axis argument lets SciPy do all the resamples in one vectorised call, and rng fixes the resampling so the interval is repeatable.

Ratings on a 1 to 5 scale are ordered but not evenly spaced: nobody can say the step from "poor" to "fair" equals the step from "good" to "excellent", so a mean rating of 3.6 is shaky. Ranks only need the order, which makes Mann-Whitney a sound choice here too:

Bash
cd ~/group-tests-demo
. .venv/bin/activate
cat > ratings.py <<'PY'
import numpy as np
from scipy import stats

import data

a, b = data.ratings()
print("rating  courier A  courier B")
for score in range(1, 6):
    print(f"{score:>6}  {(a == score).sum():>9}  {(b == score).sum():>9}")
print(f"median rating: A {np.median(a):.0f}, B {np.median(b):.0f}")

mw = stats.mannwhitneyu(a, b, alternative="two-sided")
superiority = mw.statistic / (a.size * b.size)
print(f"Mann-Whitney U = {mw.statistic:.0f}, p = {mw.pvalue:.4f}")
print(f"probability of superiority A over B (ties count half): {superiority:.2f}")
PY
python ratings.py

With 80 ratings per courier SciPy uses the normal approximation, and because ratings have many ties (dozens of 3s and 4s) it applies a tie correction. At this sample size that is fine.

Check it worked

For deliveries you see courier A's skew of 1.80 and:

Text
Mann-Whitney U = 2605, p = 0.0425
chance a random A delivery is slower than a random B delivery: 0.41
rank-biserial correlation: -0.19
median A - median B: -7.4 min, 95% bootstrap CI -14.6 to -0.3 min

For ratings you see a five-row table, medians of 4 and 3, and p = 0.0513 with a probability of superiority of 0.59. That p-value sits just above 0.05, and courier A really is rated higher in the generator. "Not significant" here means "not enough data to be sure", never "no difference".

Step 5 · Compare counts with chi-square, and small counts with Fisher's exact test

Sign-ups are yes-or-no outcomes, so the data is a 2 by 2 table of counts, not a column of measurements. The chi-square test compares each cell with the count you would expect if both screens converted at the same rate. Report the gap in percentage points alongside it, with an interval, plus the ratio of the two rates:

Bash
cd ~/group-tests-demo
. .venv/bin/activate
cat > signups.py <<'PY'
import numpy as np
from scipy import stats

import data

table = data.signups()
signed = table[:, 0]
visitors = table.sum(axis=1)
rates = signed / visitors
for name, s, n, r in zip(("screen A", "screen B"), signed, visitors, rates):
    print(f"{name}: {s} of {n} signed up ({r:.1%})")

chi = stats.chi2_contingency(table)
print(f"chi-square = {chi.statistic:.2f}, df = {chi.dof}, p = {chi.pvalue:.4f}")
print(f"smallest expected count: {chi.expected_freq.min():.0f}")

diff = rates[1] - rates[0]
se = np.sqrt((rates * (1 - rates) / visitors).sum())
z = stats.norm.ppf(0.975)
print(f"difference B - A: {diff * 100:.1f} percentage points, "
      f"95% CI {(diff - z * se) * 100:.1f} to {(diff + z * se) * 100:.1f}")
rr = stats.contingency.relative_risk(signed[1], visitors[1], signed[0], visitors[0])
rr_low, rr_high = rr.confidence_interval(confidence_level=0.95)
print(f"relative rate B / A: {rr.relative_risk:.2f}, 95% CI {rr_low:.2f} to {rr_high:.2f}")
PY
python signups.py

For a 2 by 2 table, chi2_contingency applies Yates' continuity correction by default, which makes it a little more cautious than a plain two-proportion z-test. Screen B converts about 20% better in relative terms, but the interval runs from a fraction of a point worse to 5.5 points better. That is a reason to collect more data, not to declare a winner or a loser. Plan an A/B test with a power calculation shows how to work out the sample size before you start.

The chi-square p-value is an approximation that needs enough data in every cell; the usual rule is an expected count of at least 5. Small pilots break it. Here 12 shops tried a new stock app and 11 kept the old one, and you count who ran out of stock during the month:

Bash
cd ~/group-tests-demo
. .venv/bin/activate
cat > pilot.py <<'PY'
import numpy as np
from scipy import stats

# A pilot with 12 shops on the new stock app and 11 on the old one.
# Rows: new app, old app. Columns: ran out of stock, did not.
table = np.array([[1, 11],
                  [6, 5]])

chi = stats.chi2_contingency(table)
print("expected counts if the app made no difference:")
print(chi.expected_freq.round(1))
print(f"chi-square p = {chi.pvalue:.4f} (not trustworthy here)")

fisher = stats.fisher_exact(table)
print(f"Fisher's exact p = {fisher.pvalue:.4f}")
odds = stats.contingency.odds_ratio(table)
low, high = odds.confidence_interval(confidence_level=0.95)
print(f"odds ratio {odds.statistic:.3f}, 95% CI {low:.3f} to {high:.2f}")
PY
python pilot.py

Fisher's exact test counts every table with the same row and column totals instead of leaning on an approximation, so it stays valid however small the counts. Field pilots with a handful of shops, clinics or schools are common, and this is the test to reach for with them. Look at the odds ratio's interval, though: from 0.002 to 0.98. The data is consistent with the app nearly eliminating stock-outs and with it barely helping. Twenty-three shops cannot tell those apart.

Check it worked

The sign-up script prints a smallest expected count of 170, p = 0.0715, and a difference of 2.7 percentage points with an interval from -0.1 to 5.5. The pilot script prints expected counts of 3.7 and 3.3 in the "ran out" column, both below 5, then:

Text
chi-square p = 0.0509 (not trustworthy here)
Fisher's exact p = 0.0272
odds ratio 0.086, 95% CI 0.002 to 0.98

Step 6 · Compare before and after on the same people with a paired test

The typing course data is 30 people, each measured twice. People differ hugely in typing speed (some type 25 words a minute, some 55), and that spread between people swamps a change of a few words a minute. A paired test works on each person's own change, so the differences between people drop out.

To see why that matters, run the wrong test first:

Bash
cd ~/group-tests-demo
. .venv/bin/activate
cat > training.py <<'PY'
import numpy as np
from scipy import stats

import data

before, after = data.typing_speed()
change = after - before
print(f"before: mean {before.mean():.1f} wpm, sd {before.std(ddof=1):.1f}")
print(f"after:  mean {after.mean():.1f} wpm, sd {after.std(ddof=1):.1f}")
print(f"change: mean {change.mean():.2f} wpm, sd {change.std(ddof=1):.2f}, "
      f"{(change > 0).sum()} of {change.size} people faster")

wrong = stats.ttest_ind(after, before, equal_var=False)
print(f"unpaired Welch test (wrong here): p = {wrong.pvalue:.4f}")

paired = stats.ttest_rel(after, before)
low, high = paired.confidence_interval(confidence_level=0.95)
print(f"paired t = {paired.statistic:.2f}, df = {paired.df:.0f}, p = {paired.pvalue:.6f}")
print(f"mean change 95% CI {low:.2f} to {high:.2f} wpm")
print(f"effect size (mean change / sd of change): {change.mean() / change.std(ddof=1):.2f}")

wilcoxon = stats.wilcoxon(after, before)
print(f"Wilcoxon signed-rank p = {wilcoxon.pvalue:.6f}")
PY
python training.py

The unpaired test compares two clouds of 30 speeds with a spread of about 10 each, and a 3-word gap disappears inside that. The paired test compares 30 changes whose spread is only about 3.5, and the same gap is obvious. The Wilcoxon signed-rank test is the rank-based partner of the paired t-test: use it when the changes are skewed or come from ratings.

The pairing has to be real. The arrays must be in the same person order, and "before" and "after" must be the same people. Two different classes, one before the course and one after, are independent groups and need Welch's test.

Check it worked

The script prints:

Text
change: mean 2.86 wpm, sd 3.46, 23 of 30 people faster
unpaired Welch test (wrong here): p = 0.2955
paired t = 4.52, df = 29, p = 0.000096
mean change 95% CI 1.56 to 4.15 wpm
effect size (mean change / sd of change): 0.83
Wilcoxon signed-rank p = 0.000345

The same data gives p = 0.30 one way and p = 0.0001 the other. Which test you use is part of the result.

Step 7 · See what a p-value is and is not

Two simulations make the definition concrete. First, run 2,000 experiments where both groups come from the same population, so there is nothing to find. Second, run one experiment with 200,000 bags per machine and a real but trivial 0.1 g difference:

Bash
cd ~/group-tests-demo
. .venv/bin/activate
cat > pvalues.py <<'PY'
import numpy as np
from scipy import stats

rng = np.random.default_rng(606)

# 2,000 experiments where both groups come from the same population.
a = rng.normal(500, 5, size=(2000, 50))
b = rng.normal(500, 5, size=(2000, 50))
p = stats.ttest_ind(a, b, axis=1, equal_var=False).pvalue
print(f"no real difference: {(p < 0.05).mean():.1%} of 2,000 tests gave p < 0.05")
counts, _ = np.histogram(p, bins=10, range=(0, 1))
print("p-values per tenth from 0 to 1:", " ".join(str(c) for c in counts))

# One experiment with a huge sample and a tiny real difference.
big_a = rng.normal(500.0, 5, size=200_000)
big_b = rng.normal(500.1, 5, size=200_000)
big = stats.ttest_ind(big_b, big_a, equal_var=False)
low, high = big.confidence_interval()
d = (big_b.mean() - big_a.mean()) / np.sqrt((big_a.var(ddof=1) + big_b.var(ddof=1)) / 2)
print(f"huge sample: p = {big.pvalue:.2e}, difference {big_b.mean() - big_a.mean():.3f} g "
      f"(95% CI {low:.3f} to {high:.3f}), Cohen's d {d:.3f}")
PY
python pvalues.py

axis=1 runs all 2,000 tests in one call, one per row. What the two results show:

  • A p-value is the chance of data at least this extreme if there is no difference. When there truly is none, p-values are spread evenly between 0 and 1, so about 1 test in 20 lands below 0.05 by luck. Run 20 comparisons and expect one "finding".
  • It is not the chance that the groups are the same, and 1 minus p is not the chance your idea is right.
  • It is not a measure of size. The huge sample gives p = 0.000000004 for a 0.09 g difference no customer could notice. Cohen's d of 0.02 and the interval in grams tell you that; the p-value cannot.
  • A p-value above 0.05 is not proof of no difference. The ratings and the sign-up screen both had real differences built in and both missed the line.

Check it worked

The script prints:

Text
no real difference: 5.0% of 2,000 tests gave p < 0.05
p-values per tenth from 0 to 1: 190 190 194 196 204 190 211 208 217 200
huge sample: p = 4.29e-09, difference 0.093 g (95% CI 0.062 to 0.124), Cohen's d 0.019

The ten counts are all close to 200, the flat shape you expect when nothing is going on.

Step 8 · Write each result with its size and uncertainty

A result is ready to share when a reader can see how big the difference is, how sure you are, and how you tested it, in one sentence. Put that format in a script so every comparison is reported the same way:

Bash
cd ~/group-tests-demo
. .venv/bin/activate
cat > report.py <<'PY'
import numpy as np
from scipy import stats

import data


def fmt_p(p):
    return "p < 0.001" if p < 0.001 else f"p = {p:.3f}"


a, b = data.bag_weights()
welch = stats.ttest_ind(a, b, equal_var=False)
low, high = welch.confidence_interval()
d = (a.mean() - b.mean()) / np.sqrt((a.var(ddof=1) + b.var(ddof=1)) / 2)
print(f"Bag weight: machine A bags were {a.mean() - b.mean():.1f} g heavier on average "
      f"(95% CI {low:.1f} to {high:.1f} g; Welch's t-test, {fmt_p(welch.pvalue)}; d = {d:.2f}).")

a, b = data.delivery_minutes()
mw = stats.mannwhitneyu(a, b)
boot = stats.bootstrap((a, b), lambda x, y, axis: np.median(x, axis=axis) - np.median(y, axis=axis),
                       rng=np.random.default_rng(1))
low, high = boot.confidence_interval
print(f"Delivery time: courier A's median was {np.median(b) - np.median(a):.1f} min shorter "
      f"(95% bootstrap CI {-high:.1f} to {-low:.1f} min; Mann-Whitney U, {fmt_p(mw.pvalue)}; "
      f"a random A delivery was slower than a random B delivery {mw.statistic / (a.size * b.size):.0%} of the time).")

table = data.signups()
rates = table[:, 0] / table.sum(axis=1)
se = np.sqrt((rates * (1 - rates) / table.sum(axis=1)).sum())
diff = rates[1] - rates[0]
low, high = (diff - 1.96 * se) * 100, (diff + 1.96 * se) * 100
chi = stats.chi2_contingency(table)
note = " The interval includes zero, so this is not conclusive." if low < 0 < high else ""
print(f"Sign-ups: screen B converted {diff * 100:.1f} percentage points more "
      f"(95% CI {low:.1f} to {high:.1f}; chi-square, {fmt_p(chi.pvalue)}).{note}")

before, after = data.typing_speed()
paired = stats.ttest_rel(after, before)
low, high = paired.confidence_interval()
print(f"Typing course: speed rose by {(after - before).mean():.1f} wpm on average "
      f"(95% CI {low:.1f} to {high:.1f} wpm; paired t-test, {fmt_p(paired.pvalue)}; n = {before.size}).")
PY
python report.py

Each sentence leads with the size in the reader's own units (grams, minutes, percentage points, words a minute), then gives the interval, then names the test. Rounding p-values to three places and writing very small ones as p < 0.001 stops readers from treating extra zeros as extra importance. The sign-up line says plainly that it is not conclusive, so nobody reads 2.7 points as a win.

Before you send results like these, check three things the script cannot: that each group was chosen the way you think (the couriers served similar areas, the screens were shown at random), that you decided on the comparisons before looking at the data, and how many comparisons you ran in total.

Check it worked

The script prints exactly four sentences:

Text
Bag weight: machine A bags were 3.2 g heavier on average (95% CI 0.7 to 5.7 g; Welch's t-test, p = 0.012; d = 0.49).
Delivery time: courier A's median was 7.4 min shorter (95% bootstrap CI 0.3 to 14.6 min; Mann-Whitney U, p = 0.042; a random A delivery was slower than a random B delivery 41% of the time).
Sign-ups: screen B converted 2.7 percentage points more (95% CI -0.1 to 5.5; chi-square, p = 0.071). The interval includes zero, so this is not conclusive.
Typing course: speed rose by 2.9 wpm on average (95% CI 1.6 to 4.1 wpm; paired t-test, p < 0.001; n = 30).

When you are done, delete the project with rm -rf ~/group-tests-demo.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.