typestar

Comparing two means in Python

The t-test, and the variant that does not assume equal variances.

import numpy as np
from scipy import stats

rng = np.random.default_rng(1)
before = rng.normal(90, 10, size=40)
after = rng.normal(97, 12, size=40)

welch = stats.ttest_ind(before, after, equal_var=False)
print(round(welch.statistic, 3), f"{welch.pvalue:.5f}")
print(welch.confidence_interval(0.95).low.round(2))

paired = stats.ttest_rel(before, after)
print(round(paired.statistic, 3), f"{paired.pvalue:.5f}")
print(stats.ttest_1samp(after, popmean=90).pvalue < 0.05)

How it works

  1. ttest_ind compares independent samples.
  2. equal_var=False is Welch's test, the safer default.
  3. ttest_rel is for paired measurements of the same subjects.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
469
Tokens
147
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 84 seconds.

Type this snippet

Step 1 of 4 in Hypothesis tests, step 4 of 23 in Scientific computing with SciPy.

← Previous Next →