C2.5

t检验(均值检验)

教材页 第2章
 

问题描述:
Python完成单样本t检验,两独立样本t检验,两配对样本t检验。检验方法为:t-test

Python

from scipy import stats
import numpy as np# 单样本t检验

sample1 = np.random.normal(loc=5.1, scale=1, size=100)
t_test_1samp_result = stats.ttest_1samp(sample1, 5.1)
print(f"单样本t检验结果:t值 = {t_test_1samp_result.statistic}, p值 = {t_test_1samp_result.pvalue}")# 两独立样本t检验

sample2 = np.random.normal(loc=5.2, scale=1, size=100)
t_test_ind_result = stats.ttest_ind(sample1, sample2)
print(f"两独立样本t检验结果:t值 = {t_test_ind_result.statistic}, p值 = {t_test_ind_result.pvalue}")# 两配样本t检验

paired_sample1 = np.random.normal(loc=5.1, scale=1, size=100)
paired_sample2 = np.random.normal(loc=5.2, scale=1, size=100)
t_test_rel_result = stats.ttest_rel(paired_sample1, paired_sample2)
print(f"两配样本t检验结果:t值 = {t_test_rel_result.statistic}, p值 = {t_test_rel_result.pvalue}")

输出

单样本t检验结果:t值 = -2.4155712492649353, p值 = 0.017544431649790682
两独立样本t检验结果:t值 = -2.4041306362696138, p值 = 0.017132428848110136
两配样本t检验结果:t值 = -1.5798368004543906, p值 = 0.1173341383046289

书籍 姜维.《数据分析与数据挖掘》、《数据分析与数据挖掘建模与工具》,电子工业出版社, 2023,2024。
软件 Python,C++(附加orsci包)。