One Sample T-Test in Python

DataScience-ProF
2 min readFeb 3, 2023

--

A One Sample t-test is a statistical hypothesis test that compares the mean of a single sample with a known value (usually the population mean) and tests whether the sample mean is significantly different from the population mean. In this article, we will look at how to perform a one sample t-test in Python using the ttest_1samp function from the scipy.stats module.

The first step in performing a one sample t-test is to import the scipy.stats module. This can be done using the following code:

import scipy.stats as stats

Next, we need to define our sample and the mean of the population. In this example, let’s assume our sample is [2, 3, 4, 5, 6, 7, 8, 9, 10] and the mean of the population is 5:

sample = [2, 3, 4, 5, 6, 7, 8, 9, 10]
population_mean = 5

Now, we can use the ttest_1samp function to perform the one sample t-test. The function takes two arguments: the sample and the population mean, and returns the t-statistic and the p-value. The code for performing the one sample t-test is as follows:

t_statistic, p_value = stats.ttest_1samp(sample, population_mean)

The next step is to interpret the results. If the p-value is less than a specified level of significance (usually 0.05), then the null hypothesis is rejected and it is concluded that there is a significant difference between the sample mean and the population mean. On the other hand, if the p-value is greater than 0.05, we fail to reject the null hypothesis and conclude that there is no significant difference between the sample mean and the population mean.

Here’s the code for interpreting the results:

if p_value < 0.05:
print("Reject the null hypothesis. Significant differences exist between the sample mean and the population mean.")
else:
print("Fail to reject the null hypothesis. No significant differences exist between the sample mean and the population mean.")

In conclusion, a one sample t-test is a powerful tool for determining whether there is a significant difference between the mean of a sample and a known value. With the help of the ttest_1samp function from the scipy.stats module, performing a one sample t-test in Python is easy and straightforward.

--

--

DataScience-ProF

Passionate about Data Science? I offer personalized data science training and mentorship. Join my course today to unlock your true potential in Data Science.