如何将 2 个数据帧与对同一位置的值应用函数结合起来

How to combine 2 dataframes with applying function on the values of the same position

我正在尝试合并 2 个数据帧并将函数应用于 2 个数据帧相同位置的值。

2 个数据框中的每个元素都是列表类型,表示项目 [col,row] 的向量。

df1 :

   A      B   
0  vec1   vec2      
1  vec1   vec2      
2  vec1   vec2   

df2 :

   A      B         
0  vec5   vec5     
1  vec6   vec6    
2  vec7   vec7  

function : gensim.matutils.cossim(vec1,vec2)

Expected new_df :
   A                   B
0  cossim(vec1,vec5)   cossim(vec2,vec5)   
1  cossim(vec1,vec6)   cossim(vec2,vec6)   
2  cossim(vec1,vec7)   cossim(vec2,vec7)

以下代码是我实现的:

for column in df1():
    new_df[column] = df1[column].apply(matutils.cossim(df1[x],df2.loc[0,column]))

我得到的错误是:

AttributeError: 'list' object has no attribute 'sqrt'

您可以定义自己的 function 并应用它并通过 numpy.vectorize 更改它。

import numpy as np
import pandas as pd

from sklearn.metrics.pairwise import cosine_similarity


X = pd.DataFrame([[[0.1,0.1], [0.2,0.2]], [[0.3,0.3], [0.4,0.4]]])
Y = pd.DataFrame([[[0.1,0.1], [0.2,0.2]], [[0.3,0.3], [0.4,0.4]]])

def func(vecx, vecy):
    return cosine_similarity(vecx, vecy)

F = np.vectorize(func)         

print(pd.DataFrame(F(X, Y)))

你会得到

     0    1
0  1.0  1.0
1  1.0  1.0