Merge two data frames with the closest number into a single row using pandas?

Viewed 555

I have two data frames:

df1
col1      col2
 8         A
 12        C
 20        D

df2
col1     col3
 7        F
 15       G

I want to merge these two data frames on col1 in a way that the closest value of col1 from df2 and df1 will merge in a single row.

the final data frame will look like,

df
col1    col2    col3
 8        A      F
 12       C      G
 20       D      NA

I can do this using for loop and comparing the numbers, but the execution time will be huge.

Is there any pythonic way to do it, so the runtime will be reduced. Some pandas shortcut may be.

1 Answers

Use merge_asof with direction='nearest' and tolerance parameter:

df = pd.merge_asof(df1, df2, on='col1', direction='nearest', tolerance=3)
print (df)
   col1 col2 col3
0     8    A    F
1    12    C    G
2    20    D  NaN
Related