熊猫:如何查找范围内的值的行和列?

时间:2018-10-26 18:39:58

标签: python pandas dataframe

我有一个Pandas DataFrame,它是通过对变量执行多次关联而生成的。

corr = df.apply(lambda s: df.corrwith(s))
print('\n', 'Correlations')
print(corr.to_string())

输出看起来像这样:

 Correlations
        A         B           C          D          E
A   1.000000   -0.901104    0.662530  -0.772657   0.532606
B  -0.901104    1.000000   -0.380257   0.946223  -0.830466
C   0.662530   -0.380257    1.000000  -0.227531  -0.102506
D  -0.772657    0.946223   -0.227531   1.000000  -0.888768
E   0.532606   -0.830466   -0.102506  -0.888768   1.000000

但是,这只是相关表的一小部分,可能超过300行x 300 cols。我正在尝试寻找一种方法来识别特定值范围内相关性的坐标。

例如,在<0.25> +0.25和-0.25 之间的相关性。我想要的输出将是:

E x C = -0.102506
D x C = -0.227531

在搜索中,我发现了一些无法以连贯的方式组合在一起的熊猫函数: pandas iloc, locpandas between

您如何建议我去完成此过滤?

1 个答案:

答案 0 :(得分:1)

使用遮罩+ DataFrame.where。由于相关矩阵是对称的,因此我们将使用np.triu来消除重复项。

import numpy as np

corr.where(np.triu((corr.values <= 0.25) & (corr.values >= -0.25))).stack()

C  D   -0.227531
   E   -0.102506
dtype: float64