python - 如何使用 numpy 配对 (x,y) 对

标签 python arrays numpy search bisection

我有 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/

相关文章:

Python 线性方程 - 高斯消元法

python - 转储 pickle 不适用于 rb+

python - Flask-RESTful - 上传图片

python - numpy 的百分位数函数究竟做了什么?

python - 为什么结果应该是整数,却是循环数?

python - 如何在 Jinja 中使用查找表?

c# - 无法将[]的索引应用于封装数组的 'method group'类型的表达式

Java 传递参数数组

javascript - 无法访问javascript中的数组元素

python - 运行时错误 : The current Numpy installation fails to pass a sanity check due to a bug in the windows runtime