[英]Find shortest distance between points of two arrays with scipy
I have two arrays centroids
and nodes
我有两个数组
centroids
和nodes
I need to find the shortest distance of each point in centroids
to any point in nodes
我需要找到
centroids
心中每个点到nodes
任何点的最短距离
The output for centroids
is following centroids
的输出如下
array([[12.52512263, 55.78940022],
[12.52027731, 55.7893347 ],
[12.51987146, 55.78855611]])
The output for nodes
is following nodes
的输出如下
array([[12.5217378, 55.7799275],
[12.5122589, 55.7811443],
[12.5241664, 55.7843297],
[12.5189395, 55.7802709]])
I use the following code to get the shortest distance我使用以下代码来获得最短距离
shortdist_from_centroid_to_node = np.min(cdist(centroids,nodes))
However, this is the output I get (I should get 3 lines of output)但是,这是我得到的输出(我应该得到 3 行输出)
Out[131]: 3.0575613850140956e-05
Can anyone specify what the problem is here?任何人都可以指定这里的问题是什么? Thanks.
谢谢。
When you doing np.min it return the minimal value of the 2d-array.当您执行 np.min 时,它返回二维数组的最小值。 You want the minimum value for each centroids.
您需要每个质心的最小值。
shortest_distance_to_centroid = [min(x) for x in cdist(centroids,nodes)]
To have the associate index one way would be to get the index of the corresponding value.要获得关联索引,一种方法是获取相应值的索引。 Another is to write a custom min() function that also return the index (so you parse the list only once)
另一个是编写一个自定义 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
solution with a custom function:具有自定义功能的解决方案:
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)]
I guess what you need is just add an arg called axis
, just like this:我想你需要的只是添加一个名为
axis
的参数,就像这样:
shortdist_from_centroid_to_node = np.min(cdist(centroids,nodes), axis=1)
As for the meaning of the axis arg, you could refer to numpy.min .至于轴arg的含义,可以参考numpy.min 。 All in all you need minimum on each row rather than on the whole matrix.
总而言之,您需要每一行的最小值,而不是整个矩阵。
If I am not wrong your code says you are trying to access the min
value hence you are getting a single value.如果我没有错,您的代码说您正在尝试访问
min
因此您将获得一个值。 remove np.min()
try:删除
np.min()
尝试:
shortdist_from_centroid_to_node = cdist(centroids,nodes)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.