卡方检验

使用 Python 分析调查数据

EbunOluwa Andrew

Data Scientist

卡方检验

  • 推断分类变量的分布
    • 比较观测值与期望值

骰子照片,作者 Edge2Edge Media,来自 Unsplash

使用 Python 分析调查数据

调查分析中的卡方检验

  • 判定总体中两个分类变量的关系
  • $H_{o}$ = 变量无关系
  • $H_{a}$ = 变量有关系
  • P 值
    • 若显著(<0.05),拒绝原假设
    • 若不显著(>0.05),接受原假设
使用 Python 分析调查数据

为何在调查分析中使用卡方检验

  • 选取与输出变量相关的输入变量

  • 理解不同变量对总体的影响

  • 判断差异是偶然还是具有统计显著性

调查结果照片,作者 Firmbee.com,来自 Unsplash

1 Photo by Firmbee.com on Unsplash
使用 Python 分析调查数据

调查分析中卡方检验的假设

  • 两个变量均为分类变量
  • 样本从总体中随机抽取
  • 样本量 > 100
  • 期望频数 >=5
使用 Python 分析调查数据

用于卡方分析的调查数据

pet_type current_pets time_spent reduces_stress
dog 1 420 yes
dog 1 180 yes
dog 4 30 yes
dog 1 30 yes
dog 1 60 yes
使用 Python 分析调查数据

用于卡方分析的调查数据

  • 样本量 >100
  • 两个分类变量:
    • pet_type
    • reduces_stress
  • $$H_{o} $$ 宠物类型与减压感受无关系
  • $$H_{a}$$ 宠物类型与减压感受有关
使用 Python 分析调查数据

在 Python 中对 pet_survey 进行卡方分析的步骤

import pandas as pd
import scipy.stats as st
data = pd.read_csv('pet_survey.csv') 

cross_table = pd.crosstab(data.reduces_stress, data.pet_type)
chi_analysis = st.chi2_contingency(cross_table)
print(chi_analysis)
|--------------------------|
| (67.7,                   | 
| 1.9e-16,                 |
| 1,                       |
| array([[1767.0, 1825.0], |
| [2251.0, 2325.0]]))      |
使用 Python 分析调查数据

pet_survey 的结果与解读

  • 频数 >= 5

    • 结果有效
  • p 值 < 0.05

    • 拒绝原假设
    • pet_ownedreduces_stress 有关
  • 宠物类型会影响是否感到减压

卡方检验结果

使用 Python 分析调查数据

让我们来练习!

使用 Python 分析调查数据

Preparing Video For Download...