Python 3.x - Pandas应用非常慢

时间:2016-12-20 12:58:00

标签: python pandas apply recommendation-engine

我创建了一个推荐系统。有2个数据帧 - input_df和recommended_df

input_df - 用户已查看的内容的数据框。此df用于生成建议

User_Name   Viewed_Content_Name
User1   Content1
User1   Content2
User1   Content5
User2   Content1
User2   Content3
User2   Content5
User2   Content6
User2   Content8

Recommended_df - 向用户推荐的内容的数据框

User_Name   Recommended_Content_Name
User1   Content1 # This recommendation has already been viewed by User1. Hence this recommendation should be removed
User1   Content8
User2   Content2
User2   Content7

我想删除用户已查看过的推荐内容。我尝试过两种方法,但它们都非常耗时。我需要一种方法来识别input_df和recommended_df

中行的出现

方法1 - 使用子集,对于recommended_df中的每一行,我尝试查看该行是否已在input_df中发生

for i in range(len(recommended_df)):
    recommended_df.loc[i,'Recommendation_Completed']=len(input_df [(input_df ['User_Name']== recommended_df.loc[i,'User_Name']) & (input_df ['Viewed_Content_Name']== recommended_df.loc[i,'Recommended_Content_Name'])]) 

recommended_df = recommended_df.loc[recommended_df['Recommendation_Completed']==0]
# Remove row if already occured in input_df

方法2 - 尝试使用apply

查看recommended_df中的行是否出现在input_df中

在input_df和recommended_df中创建了一个键列。这是每个用户和内容的唯一键

Input_df =

User_Name   Viewed_Content_Name    keycol (User_Name + Viewed_Content_Name)
User1   Content1    User1Content1   
User1   Content2    User1Content2
User1   Content5    User1Content5
User2   Content1    User2Content1
User2   Content3    User2Content3
User2   Content5    User2Content5
User2   Content6    User2Content6
User2   Content8    User2Content8

Recommended_df =

User_Name   Recommended_Content_Name    keycol (User_Name + Recommended_Content_Name)
User1   Content1    User1Content1
User1   Content8    User1Content8
User2   Content2    User2Content2
User2   Content7    User2Content7

recommended_df ['Recommendation_Completed'] = recommended_df ['keycol'].apply(lambda d: d in input_df ['keycol'].values)

recommended_df = recommended_df.loc[recommended_df['Recommendation_Completed']==False]
# Remove if row occurs in input_df

使用apply的第二种方法比方法1快,但如果我使用countifs函数,我仍然可以在excel中更快地做同样的事情。如何使用python更快地复制它?

1 个答案:

答案 0 :(得分:2)

尽量只使用apply作为最后的手段。您可以连接用户和内容,然后使用布尔选择。

user_content_seen = input_df.User_Name + input_df.Viewed_Content_Name

user_all = Recommended_df.User_Name + Recommended_df.Recommended_Content_Name

Recommended_df[~user_all.isin(user_content_seen)]