简体   繁体   English

最小欧氏距离

[英]Minimum Euclidean Distance

I have two dataframes (attached image).我有两个数据框(附图)。 For each of the given row in Table-1 -对于表 1 中给定的每一行 -

Part1 - I need to find the row in Table-2 which gives the minimum Euclidian distance.第 1 部分- 我需要在表 2 中找到给出最小欧几里得距离的行。 Output-1 is the expected answer.输出 1 是预期的答案。

Part2 - I need to find the row in Table-2 which gives the minimum Euclidian distance.第 2 部分- 我需要在表 2 中找到给出最小欧几里得距离的行。 Output-2 is the expected answer.输出 2 是预期的答案。 Here the only difference is that a row from Table-2 cannot be selected two times.这里唯一的区别是表 2 中的一行不能被选择两次。

I tried this code to get the distance but not sure on how to add other fields -我尝试使用此代码来获取距离,但不确定如何添加其他字段 -

import numpy as np
from scipy.spatial import distance

s1 = np.array([(2,2), (3,0), (4,1)])
s2 = np.array([(1,3), (2,2),(3,0),(0,1)])
print(distance.cdist(s1,s2).min(axis=1))

Two dataframes and the expected output:两个数据帧和预期输出:

截图

The code now gives the desired output, and there's a commented out print statement for extra output.代码现在给出了所需的输出,并且有一个注释掉的打印语句用于额外的输出。

It's also flexible to different list lengths.它对不同的列表长度也很灵活。

Credit also to: How can the Euclidean distance be calculated with NumPy?归功于如何使用 NumPy 计算欧几里得距离?

Hope it helps:希望能帮助到你:

from numpy import linalg as LA

list1 = [(2,2), (3,0), (4,1)]
list2 = [(1,3), (2,2),(3,0),(0,1)]

names = range(0, len(list1) + len(list2))
names = [chr(ord('`') + number + 1) for number in names]

i = -1
j = len(list1) #Start Table2 names
for tup1 in list1:
    collector = {} #Let's collect values for each minimum check
    j = len(list1)
    i += 1
    name1 = names[i]
    for tup2 in list2:
        name2 = names[j]
        a = numpy.array(tup1)
        b = numpy.array(tup2)
#        print ("{} | {} -->".format(name1, name2), tup1, tup2, "   ", numpy.around(LA.norm(a - b), 2))
        j += 1
        collector["{} | {}".format(name1, name2)] = numpy.around(LA.norm(a - b), 2)
        if j == len(names):
            min_key = min(collector, key=collector.get)
            print (min_key, "-->" , collector[min_key])

Output:输出:

a | e --> 0.0
b | f --> 0.0
c | f --> 1.41

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

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