Python比例测试类似于R中的prop.test

时间:2014-10-28 17:45:10

标签: python statistics scipy

我正在寻找Python中的测试:

> survivors <- matrix(c(1781,1443,135,47), ncol=2)
> colnames(survivors) <- c('survived','died')
> rownames(survivors) <- c('no seat belt','seat belt')
> survivors
             survived died
no seat belt     1781  135
seat belt        1443   47
> prop.test(survivors)

    2-sample test for equality of proportions with continuity correction

data:  survivors
X-squared = 24.3328, df = 1, p-value = 8.105e-07
alternative hypothesis: two.sided
95 percent confidence interval:
 -0.05400606 -0.02382527
sample estimates:
   prop 1    prop 2 
0.9295407 0.9684564 

我最感兴趣的是p-value计算。

示例来自here

2 个答案:

答案 0 :(得分:18)

我想我明白了:

In [11]: from scipy import stats

In [12]: import numpy as np

In [13]: survivors = np.array([[1781,135], [1443, 47]])

In [14]: stats.chi2_contingency(survivors)
Out[14]: 
(24.332761232771361,       # x-squared
 8.1048817984512269e-07,   # p-value
 1,
 array([[ 1813.61832061,   102.38167939],
       [ 1410.38167939,    79.61832061]]))

答案 1 :(得分:1)

添加到@Akavall的答案:如果您没有明确拥有“失败”计数(示例中的死亡人数),则R的prop.test可让您仅指定试验的总数,例如prop.test(c(1781, 1443), c(1781+135, 1443+47))将为您提供与您生成的列联表相同的结果。

Scipy的chi2_contingency明确要求失败计数和完整的应急表。如果您没有明确的失败计数,而只想检查两个样本中成功总数所占的比例是否相等,则可以使用来破解scipy函数

survivors = np.array([[1781, total1 - 1781], [1443, total2 - 47]])
chi2_contingency(survivors)

# Result:
(24.332761232771361, 8.1048817984512269e-07, 1,
array([[ 1813.61832061,   102.38167939],
           [ 1410.38167939,    79.61832061]]))

花些时间弄清楚这个问题。希望对别人有帮助。