Link Search Menu Expand Document (external link)

How to do a two-sided hypothesis test for a sample mean (in Python, using SciPy)

See all solutions.

Task

Say we have a population whose mean μ is known. We take a sample x1,,xn and compute its mean, x¯. We then ask whether this sample is significantly different from the population at large, that is, is μ=x¯?

Related tasks:

Solution

This is a two-sided test with the null hypothesis H0:μ=x¯. We choose a value 0α1 as the probability of a Type I error (false positive, finding we should reject H0 when it’s actually true).

1
2
3
4
5
6
7
8
9
10
11
12
from scipy import stats

# Replace these first three lines with the values from your situation.
alpha = 0.05
pop_mean = 10
sample = [ 9, 12, 14, 8, 13 ]

# Run a one-sample t-test and print out alpha, the p value,
# and whether the comparison says to reject the null hypothesis.
t_statistic, p_value = stats.ttest_1samp( sample, pop_mean )
reject_H0 = p_value < alpha
alpha, p_value, reject_H0
(0.05, 0.35845634462296455, False)

In this case, the sample does not give us enough information to reject the null hypothesis. We would continue to assume that the sample is like the population, μ=x¯.

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)