我的数据帧df
看起来像这样
review_id user_id prod_id review
0 10 5 this restaurant is the best.
1 30 10 Worst food.
2 10 15 Best place!
3 30 5 the food is too expensive.
4 30 10 Yummy! I love it.
我现在定义了一个函数ACS
,我想用它来计算每个用户的平均内容相似性。我编写了如下函数:
def ACS(rvw1,rvw2):
rvw1=rvw1.replace(",", "").replace(".", "").replace("?","").replace("!","").lower()
rvw2=rvw2.replace(",", "").replace(".", "").replace("?","").replace("!","").lower()
rvw1words = rvw1.split()
rvw2words = rvw2.split()
allwords = list(set(rvw1words) | set(rvw2words))
rvw1freq=[]
rvw2freq=[]
for word in allwords:
rvw1freq.append(rvw1words.count(word))
rvw2freq.append(rvw2words.count(word))
return np.dot(rvw1freq,rvw2freq)/(np.linalg.norm(rvw1freq)*np.linalg.norm(rvw2freq))
此函数将两个字符串作为输入,并以0到1的比例返回它们之间的相似性。我的目标是计算每个用户的内容相似性,因此我形成了一个groupby,如下所示:
grouped = df.groupby('user_id')['review']
现在我想对每个组应用我的ACS
函数(类似于grouped.ACS()
)。但问题是ACS将两个字符串作为输入并计算它们的相似性。但是groupby中的每个组可能有2个以上的审阅字符串。我应该怎么做才能将此功能应用到每个组,以便它从一个组中获取所有评论并计算它们的内容相似性。
非常感谢
可以使用
pd.merge
获得行的笛卡尔积,然后使用pd.DataFrame.apply
应用函数:相关问题 更多 >
编程相关推荐