我有 2 个 2D NumPy 数组,每个数组由 ~300,000 (x,y) 对组成。给定数组 中的第 i (x, y) 对一个 ,我需要在数组 中找到对应的第 jth (x,y) 对乙 使得 ([xi - xj]2 + [yi - yj]2)½,即两个 (x,y) 对之间的距离最小化。
我目前正在做的是argmin
像这样:
thickness = []
for i in range(len(A)):
xi = A[i][0]
yi = A[i][1]
idx = (np.sqrt(np.power(B[:, 0] - xi, 2) + np.power(B[:, 1] - yi, 2))).argmin()
thickness.append([(xi + B[idx][0]) / 2, (yi + B[idx][1]) / 2,
A[i][2] + B[idx][2]])
有没有更快的方法来实现这一点?
最佳答案
我们可以使用 Cython-powered kd-tree
for quick nearest-neighbor lookup获得最近的邻居,从而实现我们想要的输出,就像这样 -
from scipy.spatial import cKDTree
idx = cKDTree(B[:,:2]).query(A[:,:2], k=1)[1]
thickness = [(A[:,0] + B[idx,0]) / 2, (A[:,1] + B[idx,1]) / 2, A[:,2] + B[idx,2]]
关于python - 如何使用 numpy 配对 (x,y) 对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58977952/