[英]Minimum Euclidean Distance
我有两个数据框(附图)。 对于表 1 中给定的每一行 -
第 1 部分- 我需要在表 2 中找到给出最小欧几里得距离的行。 输出 1 是预期的答案。
第 2 部分- 我需要在表 2 中找到给出最小欧几里得距离的行。 输出 2 是预期的答案。 这里唯一的区别是表 2 中的一行不能被选择两次。
我尝试使用此代码来获取距离,但不确定如何添加其他字段 -
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))
两个数据帧和预期输出:
代码现在给出了所需的输出,并且有一个注释掉的打印语句用于额外的输出。
它对不同的列表长度也很灵活。
希望能帮助到你:
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])
输出:
a | e --> 0.0
b | f --> 0.0
c | f --> 1.41
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.