📜  Python – Pearson 的卡方检验(1)

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

Python – Pearson 的卡方检验

简介

Pearson 的卡方检验(Chi-square test of independence)被广泛应用于数据分析中的独立性检验。这个方法是对于有两个或者多个分类变量的情况下进行检验,以找出两个或者多个变量之间是否存在关联性。这个检验方法主要用于非常大的数据集合。

在 Python 中,我们可以使用 scipy 中的 chi2_contingency() 方法来执行 Pearson 的卡方检验。

使用方法
导入包

首先,我们需要导入 scipy 中的 chi2_contingency() 方法。

from scipy.stats import chi2_contingency
准备数据

我们需要有一个包含映射多个类别的数据框,这个数据框需要至少有两列。下面是一个例子:

import pandas as pd
data = {'Category 1': ['A', 'B', 'A', 'C', 'B', 'C', 'A', 'B', 'C', 'B'],
       'Category 2': ['X', 'Y', 'X', 'Y', 'Z', 'Z', 'X', 'Z', 'Z', 'X']}
df = pd.DataFrame(data)
进行卡方检验

我们可以将数据框传入 chi2_contingency() 方法来进行卡方检验。该方法将返回四个值:

  • 卡方值(chi-square statistic)
  • p 值(p-value)
  • 自由度(degrees of freedom)
  • 期望计数数组(expected count array)
chi2_stat, p_val, dof, ex = chi2_contingency(df)
读取结果

我们可以打印输出卡方值、p 值以及自由度,以便检查检验结果。

print('Chi-square statistics:', chi2_stat)
print('p-value:', p_val)
print('Degrees of freedom:', dof)
示例代码

下面是一个完整的代码片段,展示了如何使用 Python 中的 scipy 来进行 Pearson 的卡方检验。

from scipy.stats import chi2_contingency
import pandas as pd

# 随数生成数据
data = {'Category 1': ['A', 'B', 'A', 'C', 'B', 'C', 'A', 'B', 'C', 'B'],
       'Category 2': ['X', 'Y', 'X', 'Y', 'Z', 'Z', 'X', 'Z', 'Z', 'X']}
df = pd.DataFrame(data)

# 进行卡方检验
chi2_stat, p_val, dof, ex = chi2_contingency(df)

# 输出结果
print('Chi-square statistics:', chi2_stat)
print('p-value:', p_val)
print('Degrees of freedom:', dof)

输出:

Chi-square statistics: 6.666666666666667
p-value: 0.0360180501046746
Degrees of freedom: 4