无法从另一个数据帧在数据帧中创建列

2024-06-09 17:47:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过将值与其他数据帧匹配,在现有数据帧中创建一个新列

数据帧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')

This doesn't make sense because both dataframes are not of same sizes. Recommendation dataframe's size is given by user through console.


Tags: 数据idindex电影titlemergemoviesmovie
2条回答

你可以试试这个:

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

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

相关问题 更多 >