[英]How to set column values based on another dataframe
I'm working on a project that has two inputs of data, and I need to merge those data into only one DataFrame, based on the index of the second DataFrame. 我正在一个有两个数据输入的项目中,我需要根据第二个DataFrame的索引将这些数据合并到一个DataFrame中。
My first DataFrame looks like this: 我的第一个DataFrame如下所示:
user artist song timestamp
0 user_1 artist_1 song_1 2019-02-21 23:45
1 user_1 artist_2 song_2 2019-02-21 23:49
2 user_2 artist_2 song_3 2019-02-21 23:52
And my second DataFrame looks like this: 我的第二个DataFrame看起来像这样:
artist song
id
9A9xGpfS2eZn3T4Z artist_1 song_1
ke5EfOpcvTl0dtyR artist_2 song_2
9YjNEwfS4kX7aHvg artist_2 song_3
The result I'm looking for and that I'm not being able to obtain is the following: 我正在寻找但无法获得的结果如下:
user song_id timestamp
0 user_1 9A9xGpfS2eZn3T4Z 2019-02-21 23:45
1 user_1 ke5EfOpcvTl0dtyR 2019-02-21 23:49
2 user_2 9YjNEwfS4kX7aHvg 2019-02-21 23:52
Is there a way to obtain this result, using pandas builtin functions? 使用pandas内置函数有没有办法获得此结果?
Thanks! 谢谢!
Let df1
be your first DataFrame and df2
your second. 假设
df1
是您的第一个DataFrame,而df2
您的第二个DataFrame。 Then you can use: 然后,您可以使用:
new_df = df1.merge(df2, on=['artist', 'song'], how='left')
Then you can rename and delete as you like. 然后,您可以根据需要重命名和删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.