如何合并熊猫数据框但仅合并某些列

时间:2020-08-06 17:22:47

标签: python pandas dataframe

我必须从excel导入熊猫数据框:

Position   Sample   Measurement Type   Measurement
 1           1         A                   7.8
 1           1         A                   9.2
 2           2         A                   9.3
 2           2         A                   9.5
 3           1         B                   8.2
 3           1         B                   8.0

Position   Sample     Unique_ID    Other Column 
 1           1         ID_1            aaa
 2           2         ID_2            bbb
 3           1         ID_3            ccc

我想通过以下方式将它们结合起来:

Position   Sample   Measurement Type   Measurement  Unique_ID
 1           1         A                   7.8        ID_1     
 1           1         A                   9.2        ID_1     
 2           2         A                   9.3        ID_2
 2           2         A                   9.5        ID_2
 3           1         B                   8.2        ID_3
 3           1         B                   8.0        ID_3

在不合并“其他栏”的情况下如何获得结果?

df1 = df1.merge(df2, on=['Position', 'Sample']) 

如果我然后删除“其他列”,则可以,但是有一种方法可以指定我只希望合并“ Unique_ID”或要合并的列的列表。

谢谢

2 个答案:

答案 0 :(得分:1)

这应该满足:

df1.merge(df2[["Position", "Sample", "Unique_ID"]], on=['Position', 'Sample']) 

答案 1 :(得分:0)

您可以尝试以下操作:

# df1 is the first dataframe you've posted (content to merge into)
# df2 is the second dataframe you've posted (content to merge from)
pd.merge(df1, df2["Sample", "Unique ID"]], on="Sample", how="left")