简体   繁体   English

如何在两个数据框中找到彼此最接近的元素?

[英]How to find closest elements to each other in two dataframes?

Given two dataframes:给定两个数据框:

df_1:

c1, c2
a, 0
b, 0
c, 2

df_2:

c3, c4
d, 2
e, 3
f, 7

How would you find the closest c2 row to the closest c4 row, and create a new dataframe which has these in corresponding rows next to each other?您将如何找到最接近的 c2 行到最近的 c4 行,并创建一个新的 dataframe,其中这些行彼此相邻?

Example output:示例 output:

a, d (zero is closest to two)
b, d (second entry of zero counts as being closest to two)
c, d (this is the closest)

You could start by creating a new dataFrame which is a copy of your original dataframe containing c1, c2 .您可以从创建一个新的 dataFrame 开始,它是包含c1, c2的原始 dataframe 的副本。

Then by using an apply function on the c2 column, you can use the following command to find the closest value and assign it to another column.然后通过在c2列上使用 apply function,您可以使用以下命令找到最接近的值并将其分配给另一列。

result_index = df['col_to_search'].sub(search_value).abs().idxmin()

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

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