python - Pandas :获取相关性高的列的组合

标签 python numpy pandas

我有一个包含 6 列的数据集,我让 pandas 从中计算相关矩阵,结果如下:

               age  earnings    height     hours  siblings    weight
age       1.000000  0.026032  0.040002  0.024118  0.155894  0.048655
earnings  0.026032  1.000000  0.276373  0.224283  0.126651  0.092299
height    0.040002  0.276373  1.000000  0.235616  0.077551  0.572538
hours     0.024118  0.224283  0.235616  1.000000  0.067797  0.143160
siblings  0.155894  0.126651  0.077551  0.067797  1.000000  0.018367
weight    0.048655  0.092299  0.572538  0.143160  0.018367  1.000000

如何获得相关性高于 0.5 但各列不相等的列组合?所以在这种情况下,输出需要类似于:

[('height', 'weight')]

我试着用 for 循环来做,但我认为这不是正确/最有效的方法:

correlated = []
for column1 in columns:
    for column2 in columns:
        if column1 != column2:
            correlation = df[column1].corr(df[column2])
            if correlation > 0.5 and (column2, column1) not in correlated:
                correlated.append((column1, column2))

其中 df 是我的原始数据框。这将输出所需的结果:

[(u'height', u'weight')]

最佳答案

以下如何,使用 numpy,并假设您已经在 df 中拥有相关矩阵:

import numpy as np

indices = np.where(df > 0.5)
indices = [(df.index[x], df.columns[y]) for x, y in zip(*indices)
                                        if x != y and x < y]

这将导致 indices 包含:

[('height', 'weight')]

关于python - Pandas :获取相关性高的列的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26463714/

相关文章:

python - 测量纬度/经度坐标和 utm 坐标之间的距离

python - 递归限制是包含还是排除,额外的堆栈帧来自哪里?

python - 从 numpy.int32 数组的数据字节中有效地删除每 4 个字节

python - Pandas 中具有特定总长度的动态索引

python - 使用 df.itertuples() 中的元组,如何在条件下检索每个元组元素的列值?

python - 为什么包装类不继承基本数据类型?

python - 如何在 Win32 上的 Emacs 中运行交互式命令行 Python 应用程序?

python - Numpy 除以 0 解决方法

python - numpy数组的插值最大插值距离

python - 当您知道列和行引用时如何更改数据框中的字段值