Pandascorr()对corrwith()

2024-04-29 19:22:17 发布

您现在位置:Python中文网/ 问答频道 /正文

大熊猫提供两种不同相关函数的原因是什么?

DataFrame.corrwith(other, axis=0, drop=False): Correlation between rows or columns of two DataFrame objectsCompute pairwise

DataFrame.corr(method='pearson', min_periods=1): Compute pairwise correlation of columns, excluding NA/null values

(摘自pandas 0.20.3文档)


Tags: columnsof函数falsedataframe原因betweendrop
2条回答

基本答案:

下面是一个可能会更清楚的例子:

np.random.seed(123)
df1=pd.DataFrame( np.random.randn(3,2), columns=list('ab') )
df2=pd.DataFrame( np.random.randn(3,2), columns=list('ac') )

如@ffeast所述,使用corr比较同一数据帧中的数字列。将自动跳过非数值列。

df1.corr()

          a         b
a  1.000000 -0.840475
b -0.840475  1.000000

可以将df1&df2的列与corrwith进行比较。请注意,只有名称相同的列才会进行比较:

df1.corrwith(df2)

a    0.993085
b         NaN
c         NaN

其他选项:

如果希望pandas忽略列名并将df1的第一行与df2的第一行进行比较,则可以将df2的列重命名为与df1的列匹配,如下所示:

df1.corrwith(df2.set_axis( df1.columns, axis='columns', inplace=False))

a    0.993085
b    0.969220

注意,在这种情况下,df1和df2需要具有相同数量的列。

最后,一种厨房水槽方法:您还可以简单地水平连接两个数据集,然后使用corr()。其优点是,不管列的数量和命名方式如何,这基本上都是可行的,但缺点是,您可能获得的输出比您想要或需要的多:

pd.concat([df1,df2],axis=1).corr()

          a         b         a         c
a  1.000000 -0.840475  0.993085 -0.681203
b -0.840475  1.000000 -0.771050  0.969220
a  0.993085 -0.771050  1.000000 -0.590545
c -0.681203  0.969220 -0.590545  1.000000

第一个计算与另一个数据帧的相关性:

between rows or columns of two DataFrame objects

第二个用它自己计算

Compute pairwise correlation of columns

相关问题 更多 >