2 回答
TA贡献1833条经验 获得超4个赞
要找到最接近的两个,您需要计算距离矩阵,然后找到该矩阵中的最小值以获得彼此最接近的坐标(使用矩阵您将获得坐标的索引)。
from scipy.spatial import distance
import numpy as np
coords = np.array([
(35.0456, -85.2672),
(35.1174, -89.9711),
(35.9728, -83.9422),
(36.1667, -86.7833)
])
distances = distance.cdist(coords, coords, 'euclidean')
# If you don't do that then the distance to self will always
# be the min. distance in the matrix (always 0):
np.fill_diagonal(distances, np.inf)
min_index = (np.argmin(distances))
closest = np.unravel_index(min_index, distances.shape)
一旦closest定义了索引,您就可以获得关于最近坐标对的所有信息:
print(f"The two closest are {closest}")
print(f"They are at distance {distances[closest]}")
print(f"Resp. coordinates {coords[closest[0]]} and {coords[closest[1]]}")
输出:
The two closest are (0, 2)
They are at distance 1.6171965990565296
Resp. coordinates [ 35.0456 -85.2672] and [ 35.9728-83.9422]
最后,请注意所有这些输入也将起作用:
coords = np.array([ [35.0456, -85.2672], [35.1174, -89.9711] ])
arr1 = [35.0456, -85.2672]
arr2 = [35.1174, -89.9711]
coords = np.array([arr1, arr2])
TA贡献1818条经验 获得超7个赞
编写一个距离函数,然后使用 itertools 计算列表对之间的距离如何?
例如:
a_1 = [0,3,4,5]
a_2 = [4,7,8,9]
a_3 = [12, 34, 44]
from itertools import combinations
def distance(list1, list2):
"""Distance between two vectors."""
squares = [(p-q) ** 2 for p, q in zip(list1, list2)]
return sum(squares) ** .5
distances = []
for pair in combinations([a_1, a_2, a_3], 2):
distances.append(pair)
distances.append(distance(list(pair[0]), list(pair[1])))
结果:
[([0, 3, 4, 5], [4, 7, 8, 9]), 8.0, ([0, 3, 4, 5], [12, 34, 44]), 52.009614495783374, ([4, 7, 8, 9], [12, 34, 44]), 45.70557952810576]
添加回答
举报
