来自 pandas 列的数据的卡方

Chi-Squared for data from pandas column

我需要计算

的卡方
 CAT    Label
0   A   0.0
1   A   0.0
2   B   1.0
4   A   0.0
6   B   0.0
... ... ...
3566    C   0.0
3567    A   0.0
3568    B   0.0
3571    C   1.0

我一直在使用交叉表:

data = pd.crosstab(df['CAT'],df['Label'], margins = False)

我得到以下信息:

Label   0.0 1.0
CAT     
A   425 37
B   718 82
C   637 128

计算卡方,我得到以下结果:

contingency = pd.crosstab(df['CAT'], df['Label'])
stat, p, dof, expected = chi2_contingency(contingency)

alpha = 0.05

print('Significance=%.3f, p=%.3f' % (alpha, p))
if p <= alpha:
    print('-> Variables are associated')
else:
    print('-> Variables are not associated')

结果是

Significance=0.050, p=0.000
Variables are associated. 

您认为这种做法是否正确,结果是否可靠?当我检查不同的变量时,我也得到 p_value=0.000。我想知道,既然我有 A、B 和 C,我是否不能在这种情况下应用卡方。

您将小数位数限制为 3 位。您的 p 值可能要小得多并四舍五入为 0.000。例如,尝试将 p 的格式更改为 '.5g',也许这会显示更小的 p 值。