2014-10-20 72 views
4

我有6列,從中我讓熊貓計算相關矩陣,結果如下數據集:大熊貓:獲取列的組合,其中相關性較高

   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')] 

回答

8

如何以下,使用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')] 
+1

如果我把''index [x]''改成''columns [x]'',這個方法可行。它是否正確?如果是這樣,謝謝邁克爾! – Peter 2014-10-20 11:27:43

+0

是的,因爲行標籤與列標籤相同,所以可以使用。如果你有不同的標籤,它不會給出正確的結果。 – 2014-10-20 11:36:55