曼哈顿(P,Q)和(R,)之间的距离

Mas*_*s17 2 python arrays numpy python-3.x

我在曼哈顿距离工作.它适用于简单的for循环.但我试图避免这种循环.

import numpy as np
import random
A = np.random.randint(5, size=(10, 5))
B = [1, 3, 5, 2, 4]
for i in range(10):
    dist = sum(abs(A[i]-B))
    print("Distances: ", dist)
Run Code Online (Sandbox Code Playgroud)

有没有比这更好的方法?比如使用高级索引..谢谢你的指导.

sac*_*cuL 6

numpy

你可以在numpy内做到这一点:

>>> np.sum(np.abs(A-B), axis=1)
array([10,  6,  9,  9,  7,  7,  9,  8, 14,  8])
Run Code Online (Sandbox Code Playgroud)

将此与循环的输出进行比较:

Distances:  10
Distances:  6
Distances:  9
Distances:  9
Distances:  7
Distances:  7
Distances:  9
Distances:  8
Distances:  14
Distances:  8
Run Code Online (Sandbox Code Playgroud)

替代方案: scipy

scipy如果你想要你也可以使用(我个人更喜欢这种numpy方法):

from scipy.spatial.distance import cdist

>>> cdist(A,np.array(B).reshape(1,-1), metric='cityblock')
array([[10.],
       [ 6.],
       [ 9.],
       [ 9.],
       [ 7.],
       [ 7.],
       [ 9.],
       [ 8.],
       [14.],
       [ 8.]])
Run Code Online (Sandbox Code Playgroud)