卡方分析 - 预期频率在 (0,) 处具有零元素。错误
Chi Square Analysis - expected frequencies has a zero element at (0,). error
我正在处理我试图查看两个变量之间关联的数据,并且我在 Python 中的 Scipy 包中使用了卡方分析。
下面是两个变量的交叉表结果:
pd.crosstab(data['loan_default'],data['id_proofs'])
结果:
id_proofs 2 3 4 5
loan_default
0 167035 15232 273 3
1 46354 4202 54 1
如果我对相同的数据应用卡方,我会看到一条错误消息,指出 ValueError:预期频率的内部计算 table 在 (0,) 处有一个零元素。
代码:
from scipy.stats import chi2_contingency
stat,p,dof,expec = chi2_contingency(data['loan_default'],data['id_proofs'])
print(stat,p,dof,expec)
错误报告:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-154-63c6f49aec48> in <module>()
1 from scipy.stats import chi2_contingency
----> 2 stat,p,dof,expec = chi2_contingency(data['loan_default'],data['id_proofs'])
3 print(stat,p,dof,expec)
~/anaconda3/lib/python3.6/site-packages/scipy/stats/contingency.py in chi2_contingency(observed, correction, lambda_)
251 zeropos = list(zip(*np.where(expected == 0)))[0]
252 raise ValueError("The internally computed table of expected "
--> 253 "frequencies has a zero element at %s." % (zeropos,))
254
255 # The degrees of freedom
ValueError: The internally computed table of expected frequencies has a zero element at (0,).
问题的原因可能是什么?我该如何克服这个问题?
再看一下 chi2_contingency
的文档字符串。第一个参数 observed
必须是偶然性 table。您必须计算意外事件 table(就像您对 pd.crosstab(data['loan_default'],data['id_proofs'])
所做的那样)并将其传递给 chi2_contingency
.
我正在处理我试图查看两个变量之间关联的数据,并且我在 Python 中的 Scipy 包中使用了卡方分析。
下面是两个变量的交叉表结果:
pd.crosstab(data['loan_default'],data['id_proofs'])
结果:
id_proofs 2 3 4 5
loan_default
0 167035 15232 273 3
1 46354 4202 54 1
如果我对相同的数据应用卡方,我会看到一条错误消息,指出 ValueError:预期频率的内部计算 table 在 (0,) 处有一个零元素。
代码:
from scipy.stats import chi2_contingency
stat,p,dof,expec = chi2_contingency(data['loan_default'],data['id_proofs'])
print(stat,p,dof,expec)
错误报告:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-154-63c6f49aec48> in <module>()
1 from scipy.stats import chi2_contingency
----> 2 stat,p,dof,expec = chi2_contingency(data['loan_default'],data['id_proofs'])
3 print(stat,p,dof,expec)
~/anaconda3/lib/python3.6/site-packages/scipy/stats/contingency.py in chi2_contingency(observed, correction, lambda_)
251 zeropos = list(zip(*np.where(expected == 0)))[0]
252 raise ValueError("The internally computed table of expected "
--> 253 "frequencies has a zero element at %s." % (zeropos,))
254
255 # The degrees of freedom
ValueError: The internally computed table of expected frequencies has a zero element at (0,).
问题的原因可能是什么?我该如何克服这个问题?
再看一下 chi2_contingency
的文档字符串。第一个参数 observed
必须是偶然性 table。您必须计算意外事件 table(就像您对 pd.crosstab(data['loan_default'],data['id_proofs'])
所做的那样)并将其传递给 chi2_contingency
.