Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在指定列的dataframe中优雅地获取corr?_Python_Pandas - Fatal编程技术网

Python 如何在指定列的dataframe中优雅地获取corr?

Python 如何在指定列的dataframe中优雅地获取corr?,python,pandas,Python,Pandas,corr在pandas dataframe中是一个很好的函数,但我可能不想全部计算它们 以下是一个例子: In [17]: df = pd.DataFrame(np.reshape(np.random.rand(25), (5,5)), columns = ['a', 'b', 'c', 'd', 'e']) In [18]: df Out[18]: a b c d e 0 0.838749 0.3208

corr在pandas dataframe中是一个很好的函数,但我可能不想全部计算它们

以下是一个例子:

In [17]: df = pd.DataFrame(np.reshape(np.random.rand(25), (5,5)), columns = ['a', 'b', 'c', 'd', 'e'])

In [18]: df
Out[18]: 
          a         b         c         d         e
0  0.838749  0.320802  0.912720  0.282949  0.927854
1  0.023636  0.430230  0.204737  0.955598  0.791329
2  0.207512  0.004523  0.760046  0.879304  0.811682
3  0.787845  0.268755  0.912230  0.131329  0.999888
4  0.981292  0.867131  0.259114  0.796924  0.015595

In [19]: df.corr()
Out[19]: 
          a         b         c         d         e
a  1.000000  0.503521  0.285477 -0.631558 -0.364213
b  0.503521  1.000000 -0.676612  0.169081 -0.834762
c  0.285477 -0.676612  1.000000 -0.776287  0.680733
d -0.631558  0.169081 -0.776287  1.000000 -0.477167
e -0.364213 -0.834762  0.680733 -0.477167  1.000000
我只需要[a,b]和[c,d,e]之间的corr

这意味着:

corr(a, c) corr(a, d) corr(a, e)

corr(b, c) corr(b, d) corr(b, e)
这就是我想要的

一个简单的想法是:

df[['a', 'b']].corr(df[['c', 'd', 'e']])
但它失败了

我可以通过索引和列找到我想要的内容

但我觉得它不是很优雅,有什么想法吗?感谢您可以使用,如下所示:

res = df[['c', 'd', 'e']].apply(df[['a', 'b']].corrwith)
print(res)
输出

          c         d         e
a  0.410747 -0.503276  0.101129
b -0.595421  0.945503 -0.951547
请注意,这可能看起来并不优雅,但对于大量列来说,应该比执行corr和索引更快