首页 > 解决方案 > 合并数据框并复制相似的 ID 值

问题描述

所以我有两个不同大小的数据框,我试图合并它们,同时复制较短列表中的一个元素以匹配较大数据框的形状。

print(df1)

    Filename       Animal      Place      Food

0   user1.txt        1           0          0
1   user1.txt        0           0          1
2   user2.txt        0           1          0
3   user2.txt        0           0          1
4   user3.txt        1           0          0


print(df2)

    Filename                        Text  

0   user1.txt        "These cows make for a great steak"  
1   user2.txt        "Italy has the best pasta" 
2   user3.txt        "Sharks are my favorite animal"

我想做的是合并文件名上的 2 个数据框,但如果 df1 具有重复的“文件名”值,请保留该“文件名”的相应文本值。因此,例如,最终的数据框将如下所示:

    Filename       Animal      Place      Food     

0   user1.txt        1           0          0        "These cows make for a great steak" 
1   user1.txt        0           0          1        "These cows make for a great steak"
2   user2.txt        0           1          0        "Italy has the best pasta"
3   user2.txt        0           0          1        "Italy has the best pasta"
4   user3.txt        1           0          0        "Sharks are my favorite animal"

如果有人有任何想法,我将不胜感激。

谢谢!

标签: pythonpandasdataframe

解决方案


利用:

df3 = pd.merge(A, B, left_on='Filename', right_on='Filename')

现在,df3是您的目标数据框。


推荐阅读