列出大熊猫中大相关矩阵的最高相关对?

问题描述 投票:49回答:7

如何在Pandas的相关矩阵中找到最高相关性?关于如何用R(Show correlations as an ordered list, not as a large matrixEfficient way to get highly correlated pairs from large data set in Python or R)做到这一点有很多答案,但我想知道如何用熊猫做到这一点?在我的情况下,矩阵是4460x4460,所以不能在视觉上做。

python pandas
7个回答
64
投票

您可以使用DataFrame.values获取数据的numpy数组,然后使用NumPy函数(如argsort())来获得最相关的对。

但是如果你想在熊猫中这样做,你可以unstackorder DataFrame:

import pandas as pd
import numpy as np

shape = (50, 4460)

data = np.random.normal(size=shape)

data[:, 1000] += data[:, 2000]

df = pd.DataFrame(data)

c = df.corr().abs()

s = c.unstack()
so = s.sort_values(kind="quicksort")

print so[-4470:-4460]

这是输出:

2192  1522    0.636198
1522  2192    0.636198
3677  2027    0.641817
2027  3677    0.641817
242   130     0.646760
130   242     0.646760
1171  2733    0.670048
2733  1171    0.670048
1000  2000    0.742340
2000  1000    0.742340
dtype: float64

25
投票

@ HYRY的答案很完美。只需通过添加更多逻辑来避免重复和自我关联以及正确排序,从而建立答案:

import pandas as pd
d = {'x1': [1, 4, 4, 5, 6], 
     'x2': [0, 0, 8, 2, 4], 
     'x3': [2, 8, 8, 10, 12], 
     'x4': [-1, -4, -4, -4, -5]}
df = pd.DataFrame(data = d)
print("Data Frame")
print(df)
print()

print("Correlation Matrix")
print(df.corr())
print()

def get_redundant_pairs(df):
    '''Get diagonal and lower triangular pairs of correlation matrix'''
    pairs_to_drop = set()
    cols = df.columns
    for i in range(0, df.shape[1]):
        for j in range(0, i+1):
            pairs_to_drop.add((cols[i], cols[j]))
    return pairs_to_drop

def get_top_abs_correlations(df, n=5):
    au_corr = df.corr().abs().unstack()
    labels_to_drop = get_redundant_pairs(df)
    au_corr = au_corr.drop(labels=labels_to_drop).sort_values(ascending=False)
    return au_corr[0:n]

print("Top Absolute Correlations")
print(get_top_abs_correlations(df, 3))

这给出了以下输出:

Data Frame
   x1  x2  x3  x4
0   1   0   2  -1
1   4   0   8  -4
2   4   8   8  -4
3   5   2  10  -4
4   6   4  12  -5

Correlation Matrix
          x1        x2        x3        x4
x1  1.000000  0.399298  1.000000 -0.969248
x2  0.399298  1.000000  0.399298 -0.472866
x3  1.000000  0.399298  1.000000 -0.969248
x4 -0.969248 -0.472866 -0.969248  1.000000

Top Absolute Correlations
x1  x3    1.000000
x3  x4    0.969248
x1  x4    0.969248
dtype: float64

14
投票

没有冗余变量对的几行解决方案:

corr_matrix = df.corr().abs()

#the matrix is symmetric so we need to extract upper triangle matrix without diagonal (k = 1)
sol = (corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))
                 .stack()
                 .sort_values(ascending=False)
#first element of sol series is the pair with the bigest correlation

7
投票

结合@HYRY和@ arun的答案的一些功能,您可以使用以下方法在一行中打印数据帧df的顶级关联:

df.corr().unstack().sort_values().drop_duplicates()

注意:一个缺点是,如果你有1.0个不是自身变量的相关性,那么drop_duplicates()的添加就会删除它们


2
投票

使用itertools.combinations从pandas自己的相关矩阵.corr()中获取所有唯一的相关性,生成列表列表并将其反馈回DataFrame以使用'.sort_values'。设置ascending = True以显示最低的相关性

corrank将DataFrame作为参数,因为它需要.corr()

  def corrank(X):
        import itertools
        df = pd.DataFrame([[(i,j),X.corr().loc[i,j]] for i,j in list(itertools.combinations(X.corr(), 2))],columns=['pairs','corr'])    
        print(df.sort_values(by='corr',ascending=False))

  corrank(X) # prints a descending list of correlation pair (Max on top)

2
投票

使用下面的代码以降序查看相关性。

# See the correlations in descending order

corr = df.corr() # df is the pandas dataframe
c1 = corr.abs().unstack()
c1.sort_values(ascending = False)

0
投票

很多很好的答案在这里。我找到的最简单的方法是结合上面的一些答案。

corr = corr.where(np.triu(np.ones(corr.shape), k=1).astype(np.bool))
corr = corr.unstack().transpose()\
    .sort_values(by='column', ascending=False)\
    .dropna()
© www.soinside.com 2019 - 2024. All rights reserved.