python - pandas 中是否有类似 isin() 的函数接受条件语句而不是值来打印出高度相关的变量?

标签 python pandas dataframe correlation

假设我有一个相关矩阵数据框,例如

  A    B   C
A 1.0  0.8 0.6

B 0.8  1.0 0.1

C 0.6  0.1 1.0

我想返回值为 >0.7 的索引。我发现如果我正在寻找正好是 0.8 的值,我将使用 isin() 函数来查找行并遍历列(如此处所述:https://thispointer.com/python-find-indexes-of-an-element-in-pandas-dataframe/)。但是,由于我想要大于某个数字而不是特定值的值,因此我不确定 isin() 函数可以使用哪种替代方法。有什么建议么?如果有更好的方法来做到这一点,我想知道。

(附注:我已将通过 df.corr() 生成的相关矩阵保存为 Dataframe ds)

最佳答案

我每天使用以下方法来保持高于某个值的相关性,使用DataFrame.whereDataFrame.stack,然后列出索引:

corr = df.where(df>0.7).stack()
print(corr)

A  A    1.0
   B    0.8
B  A    0.8
   B    1.0
C  C    1.0
dtype: float64

然后得到对应的索引:

corr.index.tolist()

[('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B'), ('C', 'C')]

而且大多数时候我使用 np.fill_diagonal 来忽略相关矩阵的对角线:

np.fill_diagonal(corr.to_numpy(), 0)
corr = df.where(df>0.7).stack()
corr.index.tolist()

A  B    0.8
B  A    0.8
dtype: float64

[('A', 'B'), ('B', 'A')]

关于python - pandas 中是否有类似 isin() 的函数接受条件语句而不是值来打印出高度相关的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63979397/

相关文章:

python - 在没有端口转发的情况下连接到已知的外部 ip 和内部 ip

python - 基于多个条件如何在Python中获取DataFrame的一个子组?

python-3.x - Pandas 显示所有行的组总和

python - pandas 就地应用更新但返回 None

r - 在 data.frame 中跨列搜索的更简单的解决方案

python - while循环python故障

python - 如何使 ttk.Treeview 的行可编辑?

python - 使用 Pandas 查找自滚动高点以来的周期数

python - 使用 datetime 数据类型切片 pandas multiindex

python-3.x - 从 Pandas 数据框中仅提取数字和字符串