📜  设置并运行两个样本的独立 t 检验 - Python (1)

📅  最后修改于: 2023-12-03 15:41:44.358000             🧑  作者: Mango

设置并运行两个样本的独立 t 检验 - Python

在统计学中,独立 t 检验可以用于比较两个样本的均值是否有显著差异。在 Python 中,可以使用 scipy 库的 stats 模块实现独立 t 检验。

导入所需的库

首先我们需要导入需要用到的库,其中包括 numpy 和 scipy.stats。

import numpy as np
from scipy.stats import ttest_ind
生成样本数据

接下来我们需要生成两个样本数据。

# 生成样本1和样本2
sample1 = np.random.normal(10, 2, 100)
sample2 = np.random.normal(15, 2, 100)

这里我们生成了两个均值分别为 10 和 15,标准差为 2 的正态分布样本,每个样本的大小为 100。

进行独立 t 检验

现在我们可以使用 scipy.stats 的 ttest_ind() 函数对两个样本进行独立 t 检验。该函数需要两个样本作为输入,并返回 t 值和 p 值。

# 对两个样本进行独立 t 检验
t_statistic, p_value = ttest_ind(sample1, sample2)
显示结果

最后我们可以显示独立 t 检验的结果。

# 显示结果
print('t-statistic:', t_statistic)
print('p-value:', p_value)

这里我们将 t 值和 p 值输出到屏幕上。

Markdown 格式

下面是该程序完整的 Markdown 格式显示。

## 设置并运行两个样本的独立 t 检验 - Python

在统计学中,独立 t 检验可以用于比较两个样本的均值是否有显著差异。在 Python 中,可以使用 scipy 库的 stats 模块实现独立 t 检验。

### 导入所需的库

首先我们需要导入需要用到的库,其中包括 numpy 和 scipy.stats。

```python
import numpy as np
from scipy.stats import ttest_ind
生成样本数据

接下来我们需要生成两个样本数据。

# 生成样本1和样本2
sample1 = np.random.normal(10, 2, 100)
sample2 = np.random.normal(15, 2, 100)

这里我们生成了两个均值分别为 10 和 15,标准差为 2 的正态分布样本,每个样本的大小为 100。

进行独立 t 检验

现在我们可以使用 scipy.stats 的 ttest_ind() 函数对两个样本进行独立 t 检验。该函数需要两个样本作为输入,并返回 t 值和 p 值。

# 对两个样本进行独立 t 检验
t_statistic, p_value = ttest_ind(sample1, sample2)
显示结果

最后我们可以显示独立 t 检验的结果。

# 显示结果
print('t-statistic:', t_statistic)
print('p-value:', p_value)

这里我们将 t 值和 p 值输出到屏幕上。