How can a one sample t-test be conducted in Python?

A one sample t-test is a statistical method used to determine whether the mean of a sample is significantly different from a known population mean. In Python, this test can be conducted by first importing the necessary libraries, such as scipy.stats and numpy, and then using the function ttest_1samp() which takes in the sample data and the known population mean as parameters. The resulting output includes the t-statistic and p-value, which can be used to determine the significance of the difference between the sample mean and population mean. This allows researchers and analysts to effectively analyze data and make informed decisions based on the results of the t-test.

Conduct a One Sample T-Test in Python


A one sample t-test is used to determine whether or not the mean of a population is equal to some value.

This tutorial explains how to conduct a one sample t-test in Python.

Example: One Sample t-Test in Python

Suppose a botanist wants to know if the mean height of a certain species of plant is equal to 15 inches. She collects a random sample of 12 plants and records each of their heights in inches.

Use the following steps to conduct a one sample t-test to determine if the mean height for this species of plant is actually equal to 15 inches.

Step 1: Create the data.

First, we’ll create an array to hold the measurements of the 12 plants:

data = [14, 14, 16, 13, 12, 17, 15, 14, 15, 13, 15, 14]

Step 2: Conduct a one sample t-test.

Next, we’ll use the ttest_1samp() function from the scipy.stats library to conduct a one sample t-test, which uses the following syntax:

ttest_1samp(a, popmean)

where:

  • a: an array of sample observations
  • popmean: the expected population mean

Here’s how to use this function in our specific example:

import scipy.stats as stats

#perform one sample t-test
stats.ttest_1samp(a=data, popmean=15)

(statistic=-1.6848, pvalue=0.1201)

The t test statistic is -1.6848 and the corresponding two-sided p-value is 0.1201.

Step 3: Interpret the results.

H0µ = 15 (the mean height for this species of plant is 15 inches)

HAµ ≠15 (the mean height is not 15 inches)

Because the p-value of our test (0.1201) is greater than alpha = 0.05, we fail to reject the null hypothesis of the test. We do not have sufficient evidence to say that the mean height for this particular species of plant is different from 15 inches.

Additional Resources

How to Conduct a Two Sample T-Test in Python
How to Conduct a Paired Samples T-Test in Python

x