Python中的比例检验,类似于R中的prop.test
我在找一个用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
的计算。
这个例子是从这里拿来的。
2 个回答
6
补充一下@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]]))
我花了一些时间才搞明白这个,希望能对某些人有所帮助。
27
我想我明白了:
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]]))