在三维空间中有两个点

a = (ax, ay, az)
b = (bx, by, bz)

我想计算它们之间的距离:

dist = sqrt((ax-bx)^2 + (ay-by)^2 + (az-bz)^2)

我如何用NumPy做到这一点?我有:

import numpy
a = numpy.array((ax, ay, az))
b = numpy.array((bx, by, bz))

当前回答

import math

dist = math.hypot(math.hypot(xa-xb, ya-yb), za-zb)

其他回答

使用numpy.linalg.norm:

dist = numpy.linalg.norm(a-b)

这是因为欧氏距离是l2范数,而numpy.linalg.norm中ord参数的默认值是2。 要了解更多理论,请参阅数据挖掘介绍:

使用scipy.spatial.distance.euclidean:

from scipy.spatial import distance
a = (1, 2, 3)
b = (4, 5, 6)
dst = distance.euclidean(a, b)
import numpy as np
from scipy.spatial import distance
input_arr = np.array([[0,3,0],[2,0,0],[0,1,3],[0,1,2],[-1,0,1],[1,1,1]]) 
test_case = np.array([0,0,0])
dst=[]
for i in range(0,6):
    temp = distance.euclidean(test_case,input_arr[i])
    dst.append(temp)
print(dst)

这种解决问题方法的另一个例子:

def dist(x,y):   
    return numpy.sqrt(numpy.sum((x-y)**2))

a = numpy.array((xa,ya,za))
b = numpy.array((xb,yb,zb))
dist_a_b = dist(a,b)
import numpy as np
# any two python array as two points
a = [0, 0]
b = [3, 4]

首先将list更改为numpy数组,并像这样做:print(np.linalg.norm(np.array(a) - np.array(b)))。第二种方法直接从python列表as: print(np.linalg.norm(np.subtract(a,b)))