简体   繁体   English

使用 pandas 将具有最接近数字的两个数据帧合并到一行中?

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

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.我想合并 col1 上的这两个数据帧,使 df2 和 df1 中最接近的 col1 值合并为一行。

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.我可以使用 for 循环并比较数字来做到这一点,但执行时间会很长。

Is there any pythonic way to do it, so the runtime will be reduced.有没有什么pythonic方法可以做到这一点,所以运行时间会减少。 Some pandas shortcut may be.一些 pandas 快捷方式可能是。

Use merge_asof with direction='nearest' and tolerance parameter:使用带有direction='nearest'和容差参数的merge_asof

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM