【问题标题】:Chi-squared for determining people voting in each category用于确定在每个类别中投票的人的卡方
【发布时间】:2023-05-15 00:29:02
【问题描述】:

我的数据集包含以下列:

Voted? Political Category
1            Right
0            Left
1            Center
1            Right
1            Right
1            Right

我需要查看哪个类别与投票的人最相关。为此,我需要计算卡方。 我想要按投票分组?和政治类别才能有这样的东西:

(1, Right) : 1500 people
(0, Right) : 202 people
(1, Left): 826 people
(0, Left): 652 people
(1, Center): 431 people
(0, Center): 542 people

在 R 中,我会这样做:

yes = c(1500, 826, 431)
no  = c(212, 652, 542)
TBL = rbind(yes, no);  TBL

    [,1] [,2] [,3]
yes 1500  826  431
no   212  652  542

并申请

chisq.test(TBL, cor=F)

与:

X-squared = 630.08, df = 2, p-value < 2.2e-16

如果我使用 prop.test 会更好,因为它会给出每个政治类别中投票的人的比例。

   prop 1    prop 2    prop 3 
0.8761682 0.5588633 0.4429599 

我想在 Python 中获得相同或相似的结果。

【问题讨论】:

    标签: python scipy chi-squared scipy.stats


    【解决方案1】:

    您的数据采用contingency table 的形式。 SciPy 有函数scipy.stats.chi2_contingency 用于将卡方检验应用于列联表。

    例如,

    In [48]: import numpy as np
    
    In [49]: from scipy.stats import chi2_contingency
    
    In [50]: tbl = np.array([[1500, 826, 431], [212, 652, 542]])
    
    In [51]: stat, p, df, expected = chi2_contingency(tbl)
    
    In [52]: stat
    Out[52]: 630.0807418107023
    
    In [53]: p
    Out[53]: 1.5125346728116583e-137
    
    In [54]: df
    Out[54]: 2
    
    In [55]: expected
    Out[55]: 
    array([[1133.79389863,  978.82440548,  644.38169589],
           [ 578.20610137,  499.17559452,  328.61830411]])
    

    【讨论】:

    • 感谢沃伦。我收到错误消息:TypeError: '&lt;' not supported between instances of 'str' and 'int'。请问我如何使用数据样本获得频率值(只是一个示例),如 tbl 所示分组?谢谢
    • 文件中的原始数据是否像您在问题开头显示的那样格式化?
    • 是的。但政治类别中可能存在 NaN 值。
    • 即使在修复它们之后我也会收到错误消息。我为此问题提出了一个新问题
    最近更新 更多