# One Sample t-test in Python (with Code Example)

## Introduction

One sample t-test examines whether the mean of a population is statistically different from a known or hypothesized value. In Python, we can use the scipy.stats.ttest_1samp() to test one sample t-test.

The code statement syntax is as follows.

scipy.stats.ttest_1samp(data, popmean)

Where,

data: an array of sample observations

popmean: Expected value in the null hypothesis.

The following are steps of doing one sample t-test in Python, including data example and Python code.

## Steps of One Sample t-test in Python

### Step 1: Prepare the data

Suppose we try to test whether the population mean of Exam 1 scores is significantly different from 60. The following is the sample data we got from the population.

``````# sample data of Exam 1
Exam1=[65,70,75,80,68,95]
print(Exam1)``````

Output:

```[65, 70, 75, 80, 68, 95]
```

### Step 2: Running the test

``````import scipy.stats

# compare whether it is different from 60
scipy.stats.ttest_1samp(Exam1, 60)``````

Output:

```Ttest_1sampResult(statistic=3.4731486444257107, pvalue=0.01778909080949585)
```

### Step 3: Interpret the output of one sample t-test in Python

The null (H0) and alternative hypothesis (H1):

H0: µ =  µ0  (The population mean of Exam 1 is equal to the proposed population mean of 60.)
H1: µ ≠  µ0  (The population mean of Exam 1 is not equal to the proposed population mean of 60.)

Since the p-value = 0.018, which is smaller than 0.05, we reject the null hypothesis. Thus, we conclude that the population mean of Exam 1 is not equal to the proposed population mean of 60.

However, while we know that it is unequal to 60, we do not know whether it is higher or lower than 60. For this, we need to calculate the mean of the sample data.

``````import numpy as np

# calculate the mean of Exam 1
np.mean(Exam1)``````

Output:

`75.5`

As we can see, the mean is 75.5. Thus, we can see that the sample mean is greater than 60.

### Step 4: Write out the report for a one-sample t-test

You can write out the following report for the one-sample t-test you just conducted.

We conducted one sample t-test with the proposed population mean of 60. We found that the t value is 3.47 and the p-value is 0.018, which is smaller than 0.05. Thus, we rejected the null hypothesis. Further, the mean of the sample is 75.5. Thus, we conclude that, based on the sample data, the average grade of Exam 1 is significantly higher than 60.