0
0
Data Analysis Pythondata~5 mins

t-test with scipy.stats in Data Analysis Python

Choose your learning style9 modes available
Introduction

A t-test helps us check if two groups have different average values. It tells us if the difference is real or just by chance.

Comparing average test scores of two classes to see if one did better.
Checking if a new medicine changes blood pressure compared to no treatment.
Seeing if sales before and after a promotion are different.
Comparing average heights of plants grown with two different fertilizers.
Syntax
Data Analysis Python
from scipy import stats

# For one sample t-test
t_statistic, p_value = stats.ttest_1samp(sample_data, population_mean)

# For two independent samples t-test
t_statistic, p_value = stats.ttest_ind(sample1, sample2)

# For two related samples t-test (paired)
t_statistic, p_value = stats.ttest_rel(sample1, sample2)

Use ttest_1samp to compare one group to a known value.

Use ttest_ind for two separate groups.

Use ttest_rel for paired or matched groups.

Examples
One sample t-test: Check if sample average differs from 6.
Data Analysis Python
from scipy import stats
sample = [5, 7, 8, 6, 9]
result = stats.ttest_1samp(sample, 6)
print(result)
Two independent samples t-test: Compare averages of two groups.
Data Analysis Python
from scipy import stats
sample1 = [5, 7, 8, 6, 9]
sample2 = [4, 6, 7, 5, 8]
result = stats.ttest_ind(sample1, sample2)
print(result)
Paired t-test: Compare measurements before and after treatment on same subjects.
Data Analysis Python
from scipy import stats
before = [20, 22, 19, 24, 20]
after = [21, 23, 20, 25, 22]
result = stats.ttest_rel(before, after)
print(result)
Sample Program

This program compares average scores of two classes to see if they differ significantly.

Data Analysis Python
from scipy import stats

# Sample data: test scores of two classes
class_a = [88, 92, 85, 91, 87]
class_b = [78, 81, 79, 74, 77]

# Perform independent t-test
result = stats.ttest_ind(class_a, class_b)

print(f"t-statistic: {result.statistic:.3f}")
print(f"p-value: {result.pvalue:.3f}")
OutputSuccess
Important Notes

A small p-value (usually < 0.05) means the groups are likely different.

Make sure your data is roughly normal and samples are independent for best results.

Paired t-test is for related samples, like before and after measurements.

Summary

T-tests check if two averages are different.

Use scipy.stats functions: ttest_1samp, ttest_ind, ttest_rel.

Look at p-value to decide if difference is real.