【问题标题】:How to choose only variables that have less than a threshold of correlation in python如何在python中仅选择小于相关阈值的变量
【发布时间】:2020-11-17 19:21:02
【问题描述】:

我有一个相关数据框:

    import pandas as pd
    dt = pd.DataFrame({'var1': np.random.randn(3 * 50),
                       'var2': np.random.randn(3 * 50),
                       'var3': np.random.randn(3 * 50),
                       'var4': np.random.randn(3 * 50),
                       'var5': np.random.randn(3 * 50)})
    dt_corr = dt.corr()

我想创建一个列表,其中将包含vars,其中:

  • 这对的两个vars,对于相关性小于阈值(绝对值)的对
  • 对于具有较高相关性(绝对值)的对,只保留两个vars 之一。

我该怎么做?

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    所以你说你想检查 2 个变量之间的相关值,如果 2 个变量的值很高,你只想保留一个。 为此,您可以使用热图并从那里进行检查。然后你可以删除不需要的列。

    【讨论】:

    • 没错,但我正在寻找一个自动化的过程,这样我就不必看任何情节
    【解决方案2】:

    我的解决方法如下:

    import numpy as np
    
    threshold_corr = 0.3
    a = dt_corr.copy()
    a = a.mask(np.triu(np.ones(a.shape)).astype(bool)).stack().reset_index().rename(columns={0:'correlation'})
    list(set(list(a[np.abs(a.correlation) <= threshold_corr ]['level_0'].unique()) + list(a[np.abs(a.correlation) <= threshold_corr ]['level_1'].unique())))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多