假设我有以下df
:
Company Apples Mangoes Oranges
Amazon 0.75 0.6 0.98
BellTM 0.23 0.75 0.14
Cadbury 0.4 0.44 0.86
然后是另一个称为vendor
:的数据帧
Company Apples Mangoes Oranges
Deere 0.11 0.3 0.79
我想在vendor
数据帧中找到每个公司与公司Deere
的行相关性。我希望将输出的相关系数作为一列Correlationcoeff添加到原始数据帧df:中
Company Apples Mangoes Oranges Corrcoef
Amazon 0.75 0.6 0.98 0.77955981
BellTM 0.23 0.75 0.14 -0.37694478
Cadbury 0.4 0.44 0.86 0.98092707
当我尝试以下操作时:
df.iloc[:,1:].corrwith(vendor.iloc[:,1:], axis=1)
我得到一个包含NaN值的列表。我通过将每一行保存为数组并使用np.corrcoef(x1,y)
手动获得Corrcove值
您需要在corrwith中使用一个系列。
您可以使用:
df.set_index('Company').corrwith(vendor.set_index('Company').loc['Deere'], axis=1)
输出:
Company
Amazon 0.779560
BellTM -0.376945
Cadbury 0.980927
dtype: float64
使用您的代码:
df.iloc[:, 1:].corrwith(vendor.iloc[0,1:].astype(float), axis=1)
输出:
0 0.779560
1 -0.376945
2 0.980927
dtype: float64