T-Test in Python with scipy.stats
Check whether two group averages really differ with scipy.stats.ttest_ind, and read the p-value correctly.
- Independent samples with ttest_ind
- Welch's test with equal_var=False
- One-sample tests and the p-value
- 82.0
- 74.5
- t = 4.728
- p = 0.00020
Is the difference bigger than chance?
The problem
Class A scored higher than class B, but would the difference disappear with other students? Statistics courses, lab reports and A/B tests all need a way to tell a real difference from random variation.
Think of it like this
A t-test is like judging whether two dice are different by rolling each many times. A small gap between the averages could just be luck; a big gap with little spread is hard to explain by luck alone.
class_a, class_b🎲 The rolls of each dieresult.statistic📏 The gap measured in units of spreadresult.pvalue🍀 How likely luck alone gives a gap this bigp < 0.05✅ Too unlikely to be luck: call it significantA two-sample t-test compares the means of two groups. scipy.stats.ttest_ind(a, b) returns the t statistic and the p-value, the probability of a difference at least this large if the true means were equal.
Key points
ttest_indis for two independent groups;equal_var=Falseruns Welch's test.- Here t = 4.728 and p = 0.00020, below 0.05, so the difference is significant.
ttest_1samp(class_b, popmean=80)compares one group with a fixed value.- A small p-value does not say the difference is large or important, only that it is unlikely to be chance.
When should you use it?
- Lab reports and statistics assignments.
- A/B tests comparing two versions.
- Comparing two treatments or teaching methods.
When not to use it
- The same people measured twice: use the paired test
ttest_rel. - More than two groups: use ANOVA (
scipy.stats.f_oneway).
Example code
from scipy import stats
# Test scores of two classes taught with different methods
class_a = [78, 82, 85, 88, 75, 80, 84, 79, 86, 83]
class_b = [72, 75, 78, 70, 74, 77, 73, 76, 71, 79]
# Independent two-sample t-test (Welch's version: equal_var=False)
result = stats.ttest_ind(class_a, class_b, equal_var=False)
print(f"Mean A = {sum(class_a) / len(class_a):.1f}, mean B = {sum(class_b) / len(class_b):.1f}")
print(f"t = {result.statistic:.3f}, p = {result.pvalue:.5f}")
alpha = 0.05
if result.pvalue < alpha:
print("p < 0.05: the difference is statistically significant")
else:
print("p >= 0.05: no significant difference")
# One-sample t-test: is class B's mean different from 80?
one = stats.ttest_1samp(class_b, popmean=80)
print(f"Class B vs 80: t = {one.statistic:.3f}, p = {one.pvalue:.6f}")
Result of running the code
Mean A = 82.0, mean B = 74.5
t = 4.728, p = 0.00020
p < 0.05: the difference is statistically significant
Class B vs 80: t = -5.745, p = 0.000278
Code explanation
class_a and class_b are two independent groups, so ttest_ind is the right test; equal_var=False selects Welch's t-test, which does not assume both groups vary equally. The means are 82.0 and 74.5, t = 4.728 and p = 0.00020. A p-value below the chosen alpha of 0.05 means a difference this large would be very unlikely if both methods were equally good. ttest_1samp compares one group with a fixed value, here 80.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Common mistakes
Using ttest_ind for before and after scores
Measurements of the same students are paired, not independent.
stats.ttest_ind(before, after)
stats.ttest_rel(before, after)
Reading p as the chance the hypothesis is true
p is the chance of data this extreme if there were no difference, not the chance there is no difference.
# p = 0.0002, so there is a 0.02% chance the methods are equal
# p = 0.0002: a gap this big would be very unlikely if the methods were equal
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challengesTools for this lesson
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.
- NumPy Online: Run NumPy Code in Your BrowserA NumPy playground with no install: arrays, statistics, linear algebra, random numbers and broadcasting. NumPy 2, pandas and SciPy ready to import.