![](/img/trans.png)
[英]Finding index of nearest point in numpy arrays of x and y coordinates
[英]Finding nearest points in numpy arrays of x and y coordinates
我有兩個數組:
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 中的每個點,我需要在 b 中找到與該點在比率 r 內最接近的最近點。
我已經嘗試做類似於以下示例的操作:“ 在 x 和 y 坐標的 numpy 數組中查找最近點的索引”但沒有退出,有人可以向我展示使用 spatial.KDTree 或 spatial.cKDTree 的簡單方法嗎?
找到距離可以這樣完成:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.