Python - 列聯表的獨立性檢驗(卡方檢驗)
想對兩個或兩個以上因子彼此之間是否相互獨立做檢驗時,就要用到卡方檢驗,原以為在Python中實現會像R的chisq.test一樣簡便,但scipy的stats模塊功能實在分得太細,之前查到的是stats中的chisquare方法,但嘗試過后發現chisquare實際上是做適合性檢驗的。
e.g. 三種農葯的殺蟲數據
殺蟲效果 | 甲 | 乙 | 丙 |
---|---|---|---|
死亡數 | 37 | 49 | 23 |
未死亡數 | 150 | 100 | 57 |
分析殺蟲效果與農葯類型是否有關
import numpy as np from scipy.stats import chi2_contingency d = np.array([[37, 49, 23], [150, 100, 57]]) chi2_contingency(d)
輸出為:
(7.6919413561281065,
0.021365652322337315,
2,
array([[ 48.99759615, 39.04086538, 20.96153846],
[ 138.00240385, 109.95913462, 59.03846154]]))
第一個值為卡方值,第二個值為P值,第三個值為自由度,第四個為與原數據數組同維度的對應理論值
具體參考文檔:scipy.stats.chi2_contingency