Manhattan Distance between (P, Q) and (R,)

Viewed 1557

I am working on Manhattan distance. It works well with the simple for loop. But I am trying to avoid this for loop.

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)

Is there any optimal way than this? such as using advanced indexing.. Thank you for the guidance.

2 Answers

Pure numpy

You can do this within numpy:

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

Compare this to the output from your loop:

Distances:  10
Distances:  6
Distances:  9
Distances:  9
Distances:  7
Distances:  7
Distances:  9
Distances:  8
Distances:  14
Distances:  8

Alternative: scipy

You could also use scipy if you wanted (personally I prefer the numpy method though):

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.]])

Wouldn't you use radians, or degrees, and calculate the result? This should work for you.

from math import sin, cos, sqrt, atan2, radians

# approximate radius of earth in km
R = 6373.0

lat1 = radians(40.7619087)
lon1 = radians(-73.9690218)
lat2 = radians(40.760178)
lon2 = radians(-74.0037083)

dlon = lon2 - lon1
dlat = lat2 - lat1

a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))

distance = R * c

print("Result:", distance)
print("Should be:", distance, "mi")
Related