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.
0
0
t-test (ttest_ind, ttest_rel) in SciPy
Introduction
Comparing test scores of two different classes to see if one did better.
Checking if a new medicine changes blood pressure compared to no treatment.
Seeing if a diet affects weight by comparing before and after weights of the same people.
Comparing sales numbers between two stores to find if one sells more.
Syntax
SciPy
from scipy.stats import ttest_ind, ttest_rel # Independent t-test (two separate groups) ttest_ind(sample1, sample2, equal_var=True) # Paired t-test (same group, two conditions) ttest_rel(sample1, sample2)
ttest_ind is for two independent groups (like two different classes).
ttest_rel is for paired data (like before and after measurements of the same people).
Examples
This compares two different groups to see if their averages differ.
SciPy
from scipy.stats import ttest_ind group1 = [20, 22, 19, 24, 30] group2 = [25, 27, 29, 24, 28] result = ttest_ind(group1, group2) print(result)
This compares measurements before and after on the same subjects.
SciPy
from scipy.stats import ttest_rel before = [100, 102, 98, 105, 110] after = [102, 104, 100, 108, 115] result = ttest_rel(before, after) print(result)
Sample Program
This program runs both an independent t-test and a paired t-test and prints the test statistic and p-value for each.
SciPy
from scipy.stats import ttest_ind, ttest_rel # Independent samples example group_a = [12, 15, 14, 10, 13] group_b = [22, 25, 19, 24, 20] independent_test = ttest_ind(group_a, group_b) # Paired samples example before_treatment = [100, 102, 98, 105, 110] after_treatment = [102, 104, 100, 108, 115] paired_test = ttest_rel(before_treatment, after_treatment) print(f"Independent t-test result: statistic={independent_test.statistic:.3f}, pvalue={independent_test.pvalue:.3f}") print(f"Paired t-test result: statistic={paired_test.statistic:.3f}, pvalue={paired_test.pvalue:.3f}")
OutputSuccess
Important Notes
A small p-value (usually less than 0.05) means the groups are likely different.
Use ttest_ind for different groups and ttest_rel for paired data.
Check if your data meets assumptions like normal distribution for best results.
Summary
T-tests compare averages between two groups.
ttest_ind is for independent groups; ttest_rel is for paired samples.
Look at the p-value to decide if the difference is meaningful.