hel*_*ker 5 python numpy scipy euclidean-distance
我有一个数组描述了折线(连接的直线段的有序列表),如下所示:
points = ((0,0),
(1,2),
(3,4),
(6,5),
(10,3),
(15,4))
points = numpy.array(points, dtype=float)
Run Code Online (Sandbox Code Playgroud)
目前,我使用以下循环获得段距离列表:
segdists = []
for seg in xrange(points.shape[0]-1):
seg = numpy.diff(points[seg:seg+2], axis=0)
segdists.append(numpy.linalg.norm(seg))
Run Code Online (Sandbox Code Playgroud)
相反,我希望使用一些原生的Scipy/Numpy函数来应用单个函数调用,而不使用循环.
我能得到的最接近的是:
from scipy.spatial.distance import pdist
segdists = pdist(points, metric='euclidean')
Run Code Online (Sandbox Code Playgroud)
但在后一种情况下,segdists提供了每个距离,我想只得到相邻行之间的距离.
另外,我宁愿避免创建自定义函数(因为我已经有了一个可行的解决方案),而是使用更多的"numpythonic"使用本机函数.
War*_*ser 11
这是一种方式:
使用矢量化np.diff
来计算增量:
d = np.diff(points, axis=0)
Run Code Online (Sandbox Code Playgroud)
然后np.hypot
用来计算长度:
segdists = np.hypot(d[:,0], d[:,1])
Run Code Online (Sandbox Code Playgroud)
或者使用更明确的计算:
segdists = np.sqrt((d ** 2).sum(axis=1))
Run Code Online (Sandbox Code Playgroud)