使用scipy查找两个阵列点之间的最短距离

2024-10-04 01:28:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数组centroidsnodes

我需要找到centroids中每个点到nodes中任何点的最短距离

centroids的输出如下

array([[12.52512263, 55.78940022],
       [12.52027731, 55.7893347 ],
       [12.51987146, 55.78855611]])
       

nodes的输出如下

array([[12.5217378, 55.7799275],
       [12.5122589, 55.7811443],
       [12.5241664, 55.7843297],
       [12.5189395, 55.7802709]])

我使用以下代码获得最短距离

shortdist_from_centroid_to_node = np.min(cdist(centroids,nodes))

然而,这是我得到的输出(我应该得到3行输出)

Out[131]: 3.0575613850140956e-05

有人能说明问题出在哪里吗?谢谢


Tags: to代码fromnodenp数组outmin
3条回答

如果我没有弄错的话,您的代码会说您正在尝试访问min值,因此您会得到一个值。删除np.min()尝试:

shortdist_from_centroid_to_node = cdist(centroids,nodes)

我想您需要的只是添加一个名为axis的arg,如下所示:

shortdist_from_centroid_to_node = np.min(cdist(centroids,nodes), axis=1)

至于轴arg的含义,您可以参考numpy.min。总而言之,您需要在每一行上使用最小值,而不是在整个矩阵上使用最小值

执行np.min时,它返回2d数组的最小值。 您需要每个质心的最小值

shortest_distance_to_centroid = [min(x) for x in cdist(centroids,nodes)]

要获得关联索引,一种方法是获取对应值的索引。另一种方法是编写一个自定义的min()函数,该函数也会返回索引(因此只能解析列表一次)

[(list(x).index(min(x)), min(x)) for x in cdist(centroids,nodes)]  # the cast list() is needed because numpy array don't have index methods

具有自定义功能的解决方案:

def my_min(x):
       current_min = x[0]
       current_index = [1]

       for i, v in enumerate(x[1:]):
              if v < current_min:
                     current_min = v
                     current_index = i + 1
       return (current_index, current_min)

[my_min(x) for x in cdist(centroids,nodes)]

相关问题 更多 >