首页 > 解决方案 > 无法从另一个数据框中创建数据框中的列

问题描述

我正在尝试通过将值与其他数据框匹配来在现有数据框中创建一个新列。

数据框 1 - (电影)

index  |  rating  | movie_id  |  movie_title
--------------------------------------------
0      |    5     |    100    |  Inception
1      |    4     |    101    |  Starwars

数据框 2 - (建议)

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')

这没有意义,因为两个数据帧的大小不同。推荐数据框的大小由用户通过控制台给出。

标签: pythonpandas

解决方案


你可以试试这个:

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

推荐阅读