python - 使用numpy计算数组连续点之间的欧氏距离

标签 python numpy scipy euclidean-distance

我有一个数组,它描述了一条折线(连接直线段的有序列表),如下所示:

points = ((0,0),
          (1,2),
          (3,4),
          (6,5),
          (10,3),
          (15,4))
points = numpy.array(points, dtype=float)

目前,我使用以下循环获取线段距离列表:

segdists = []
for seg in xrange(points.shape[0]-1):
    seg = numpy.diff(points[seg:seg+2], axis=0)
    segdists.append(numpy.linalg.norm(seg))

相反,我想使用一些 native Scipy/Numpy 函数来应用单个函数调用,没有循环。

我能得到的最接近的是:

from scipy.spatial.distance import pdist
segdists = pdist(points, metric='euclidean')

但在后一种情况下,segdists 提供了每个距离,我只想获取相邻行之间的距离。

此外,我宁愿避免创建自定义函数(因为我已经有了一个可行的解决方案),而是更多地使用原生函数的“numpythonic”。

最佳答案

这是一种方法:

使用向量化的 np.diff计算增量:

d = np.diff(points, axis=0)

然后使用np.hypot计算长度:

segdists = np.hypot(d[:,0], d[:,1])

或者使用更明确的计算:

segdists = np.sqrt((d ** 2).sum(axis=1))

关于python - 使用numpy计算数组连续点之间的欧氏距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13590484/

相关文章:

python - 快速稀疏矩阵乘法,无需分配密集数组

python - 从同一模型中的其他类获取模型属性

python - 对 pandas MultiIndex 数据帧进行重新采样

python:无噪音 3-D 旋转?

python - 绘制从一组到另一组的复杂函数

python - 3d numpy 数组的模式/中值/平均值

python - 在 Debian 8 上使用 pip 安装 Python 3.5

python - 为什么 a**2 != a * a 对于一些花车?

python - 如何按不在数据框中的数组对数据框进行排序

python - 使用 SciPy 数值求解 ODE