如何使用以下代码构建 cramer-v 矩阵?

How do i build a cramer-v matrix using the below code?

我正在尝试使用 cramers 创建一个 heatmap/correlation 矩阵。我发现下面的代码可以帮助我解决这个问题,但是当使用 itertools.combinations 时,它不会 return 与自身组合,例如0,0 1,1 等所以我的矩阵是完全错误的,因为当一个列与自身进行比较时,对角线应该是 1 但它们是 0。我的 20 列中除了 2 列之外都是绝对的,这就是为什么我使用 cramers

def cramers_corrected_stat(confusion_matrix):
    """ calculate Cramers V statistic for categorical-categorical association.
        uses correction from Bergsma and Wicher, 
        Journal of the Korean Statistical Society 42 (2013): 323-328
    """
    chi2 = ss.chi2_contingency(confusion_matrix)[0]
    n = confusion_matrix.sum().sum()
    phi2 = chi2/n
    r,k = confusion_matrix.shape
    phi2corr = max(0, phi2 - ((k-1)*(r-1))/(n-1))    
    rcorr = r - ((r-1)**2)/(n-1)
    kcorr = k - ((k-1)**2)/(n-1)
    return np.sqrt(phi2corr / min( (kcorr-1), (rcorr-1))) 


cols = df.columns.to_list()
corrM = np.zeros((len(cols),len(cols)))
# there's probably a nice pandas way to do this
for col1, col2 in itertools.combinations(cols, 2):
    idx1, idx2 = cols.index(col1), cols.index(col2)
    corrM[idx1, idx2] = cramers_corrected_stat(pd.crosstab(df[col1], df[col2]))
    corrM[idx2, idx1] = corrM[idx1, idx2]

我该如何解决这个问题?

我写了一些东西:github.com/shakedzy/dython

nominal 下寻找 associations