找到x和y坐标的numpy数组中的最近点

时间:2016-03-30 09:37:02

标签: python scipy

我有两个数组:

a=np.array([[ 41.0,  0.71],
       [ 41.21,  0.87],
       [ 41.14,  0.96],
       [41.5,  0.86])

b=np.array([[ 41.41, 1.51],
       [ 41.3,  0.95],
       [ 41.0,  0.96],
       [42.1,  0.76]),
       [ 40.3,  0.85],
       [ 41.1,  0.76],
       [40.9,  0.96])...]

对于a中的每个点,我需要在比率r中找到b中最接近该点的最近点。

我已经尝试做类似于示例的事情:" Finding index of nearest point in numpy arrays of x and y coordinates" 但没有退出,有人可以告诉我一个简单的方法来使用spatial.KDTree或spatial.cKDTree?

1 个答案:

答案 0 :(得分:-1)

找到距离可以这样做:

In [1]: import numpy as np

In [2]: a=np.array([[ 41.0,  0.71], [ 41.21,  0.87], [ 41.14,  0.96], [41.5,  0.86]])

In [3]: b=np.array([[ 41.41, 1.51], [ 41.3,  0.95], [ 41.0,  0.96],[42.1,  0.76], [ 40.3,  0.85], [ 41.1,  0.76],[40.9,  0.96]])

计算a[0]b(4)中所有点之间的x和y之差,然后将其与(5)平方。

In [4]: c = b - a[0]

In [5]: c*c
Out[5]: 
array([[ 0.1681,  0.64  ],
       [ 0.09  ,  0.0576],
       [ 0.    ,  0.0625],
       [ 1.21  ,  0.0025],
       [ 0.49  ,  0.0196],
       [ 0.01  ,  0.0025],
       [ 0.01  ,  0.0625]])

将内部数组上的c的平方求和,得到距离的平方,然后计算平方根。

In [6]: np.sqrt(np.sum(c*c, axis=1))
Out[6]: 
array([ 0.89894382,  0.38418745,  0.25      ,  1.10113578,  0.71386273,
        0.1118034 ,  0.26925824])

这是a[0]b中每个点的距离。

找到最低要求:

In [8]: np.min(np.sqrt(np.sum(c*c, axis=1)))
Out[8]: 0.1118