Home » How to Calculate Manhattan Distance in Python (With Examples)

How to Calculate Manhattan Distance in Python (With Examples)

by Tutor Aspire

The Manhattan distance between two vectors, A and B, is calculated as:

Σ|Ai – Bi|

where i is the ith element in each vector.

This distance is used to measure the dissimilarity between two vectors and is commonly used in many machine learning algorithms.

This tutorial shows two ways to calculate the Manhattan distance between two vectors in Python.

Method 1: Write a Custom Function

The following code shows how to create a custom function to calculate the Manhattan distance between two vectors in Python:

from math import sqrt

#create function to calculate Manhattan distance 
def manhattan(a, b):
    return sum(abs(val1-val2) for val1, val2 in zip(a,b))
 
#define vectors
A = [2, 4, 4, 6]
B = [5, 5, 7, 8]

#calculate Manhattan distance between vectors
manhattan(A, B)

9

The Manhattan distance between these two vectors turns out to be 9.

We can confirm this is correct by quickly calculating the Manhattan distance by hand:

Σ|Ai – Bi| = |2-5| + |4-5| + |4-7| + |6-8| = 3 + 1 + 3 + 2 = 9.

Method 2: Use the cityblock() function

Another way to calculate the Manhattan distance between two vectors is to use the cityblock() function from the SciPy package:

from scipy.spatial.distance import cityblock

#define vectors
A = [2, 4, 4, 6]
B = [5, 5, 7, 8]

#calculate Manhattan distance between vectors
cityblock(A, B)

9

Once again the Manhattan distance between these two vectors turns out to be 9.

Note that we can also use this function to find the Manhattan distance between two columns in a pandas DataFrame:

from scipy.spatial.distance import cityblock
import pandas as pd

#define DataFrame
df = pd.DataFrame({'A': [2, 4, 4, 6],
                   'B': [5, 5, 7, 8],
                   'C': [9, 12, 12, 13]})

#calculate Manhattan distance between columns A and B 
cityblock(df.A, df.B)

9

Additional Resources

How to Calculate Euclidean Distance in Python
How to Calculate Hamming Distance in Python
How to Calculate Levenshtein Distance in Python
How to Calculate Mahalanobis Distance in Python

You may also like