【发布时间】:2023-12-08 23:29:01
【问题描述】:
我有一个二维数组,我想尽快找到每个(x, y) 点到其最近邻居的距离。
我可以使用scipy.spatial.distance.cdist:
import numpy as np
from scipy.spatial.distance import cdist
# Random data
data = np.random.uniform(0., 1., (1000, 2))
# Distance between the array and itself
dists = cdist(data, data)
# Sort by distances
dists.sort()
# Select the 1st distance, since the zero distance is always 0.
# (distance of a point with itself)
nn_dist = dists[:, 1]
这可行,但我觉得它的工作量太大,KDTree 应该能够处理这个问题,但我不确定如何处理。我对最近邻居的坐标不感兴趣,我只想要距离(并且尽可能快)。
【问题讨论】:
-
那么您为什么不继续尝试
cKDTree?只需几行代码。 -
我没想到要尝试
cKDTree。我试试看。
标签: python numpy scipy nearest-neighbor euclidean-distance