我试图通过将值与另一个数据框进行匹配在现有数据框中创建一个新列。
index | rating | movie_id | movie_title
--------------------------------------------
0 | 5 | 100 | Inception
1 | 4 | 101 | Starwars
index | rating | movie_id
------------------------------
0 | 3.9 | 101
1 | 4.7 | 100
index | rating | movie_id | movie_title
--------------------------------------------
0 | 3.9 | 101 | Starwars
1 | 4.7 | 100 | Inception
pd.merge(movies , recommendations, on ='movie_id', how ='left')
这没有意义,因为两个数据帧的大小都不相同。推荐数据帧的大小由用户通过控制台指定。
答案 0 :(得分:1)
在df1
中创建一个匹配行的字典作为键,并将要传送的值作为字典值
d=dict(zip(df1.movie_id,df1.movie_title))
使用df.map()
方法将字典中的值映射到df2
df2['movie_title']=df2['movie_id'].map(d)
index rating movie_id movie_title
0 0 3.9 101 Starwars
1 1 4.7 100 Inception
答案 1 :(得分:1)
您可以尝试以下方法:
newdf=pd.merge(recommendations,movies[movies.columns[1:]], how='left',on='movie_id')
print(newdf)
输出:
rating movie_id movie_title
0 3.9 101 Starwars
1 4.7 100 Inception