【问题标题】:iven a column find the highest correlated variable with the specified column给定一列,找到与指定列相关的最高变量
【发布时间】:2020-09-18 15:01:20
【问题描述】:

如标题所示,我有一个名为 df 的数据框。

给定一个变量(df 的指定列),我想找到与该变量相关值最高的列。

到目前为止,这是我尝试过的:

def highest_correlated(df, column):
   sol = -1
   for col in df.columns:
       while col != column:
             corr = df[column].corr(df[col])
             if corr>sol:
                sol = corr
  return sol
      

这样做的问题是花费了太多时间,最后我没有得到任何结果,任何人都可以帮我找到解决方案吗?

【问题讨论】:

    标签: python pandas correlation


    【解决方案1】:

    一个展示概念的小例子

    df = pd.DataFrame(np.random.random((5,5)), columns=list('abcde'))
    df
              a         b         c         d         e
    0  0.813973  0.948999  0.291432  0.081816  0.590892
    1  0.117661  0.371609  0.420920  0.007232  0.596047
    2  0.285615  0.840326  0.261307  0.839936  0.050935
    3  0.215191  0.236140  0.588104  0.718885  0.047986
    4  0.363681  0.280523  0.249036  0.712143  0.463029
    

    现在找到相关性最高的列

    df.corr()['a']
    a    1.000000
    b    0.686173
    c   -0.464374
    d   -0.297666
    e    0.385181
    

    我们得到的列'a'除外

    df.corr()['a'][1:].abs().idxmax()
    'b'
    

    如果你不能方便地排列列

    df.corr()['a'].drop('a').abs().idxmax()
    'b'
    

    【讨论】:

    • 感谢您的回答,如果我们假设我们不知道“a”列的位置,答案会是什么,因为您认为它是第一列
    猜你喜欢
    • 2020-03-05
    • 2021-08-25
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    相关资源
    最近更新 更多