2013-07-22 102 views

回答

27

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

但是,如果你想这样做的熊猫,你可以unstackorder数据框:

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.order(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 
+5

随着Pandas v 0.17.0及更高版本,您应该使用sort_values而不是order。如果您尝试使用订单方法,您将会遇到错误。 – Friendm1

8

@ 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 
+3

而不是get_redundant_pairs(df),可以使用“cor.loc [:,:] = np.tril(cor.values,k = -1)”,然后是“cor = cor [cor> 0]” – Sarah

4

几行方案,不会对冗余的变量:

corr_matrix = df.corr().abs() 

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

使用itertools.combinations摆脱熊猫自己的相关矩阵.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) 
+0

代码片段可能是解决方案,[包括解释](// meta.stackexchange.com/questions/114762/explaining-entirely-基于代码的答案)确实有助于提高帖子的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。 – haindl