-1

I have to pandas dataframes imported from 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

and

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

I would like to combine them this way:

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

How can I get the result without the 'Other Column' merging as well?

Doing

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

Works if I then delete the 'Other Column' but it there a way to specify I only want to merge 'Unique_ID' or a list of columns I want to merge.

Thanks

Agustin
  • 1,458
  • 1
  • 13
  • 30

2 Answers2

1

This should suffice:

df1.merge(df2[["Position", "Sample", "Unique_ID"]], on=['Position', 'Sample']) 
Piyush Singh
  • 2,736
  • 10
  • 26
0

You can try the following:

# 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")
Alex Douglas
  • 191
  • 7