gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:53:39 25 4
gpt4 key购买 nike

我有两个数据框:

df1
col1 col2
8 A
12 C
20 D

df2
col1 col3
7 F
15 G

我想以一种方式合并 col1 上的这两个数据帧,即 df2 和 df1 中最接近的 col1 值将合并在一行中。

最终的数据框看起来像,
df
col1 col2 col3
8 A F
12 C G
20 D NA

我可以使用 for 循环并比较数字来做到这一点,但执行时间会很长。

有没有什么pythonic的方法可以做到这一点,所以运行时间会减少。一些 Pandas 捷径可能是。

最佳答案

使用 merge_asof direction='nearest'和公差参数:

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

关于python - 使用pandas将具有最接近数字的两个数据框合并到一行中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58536044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com