How to Calculate Manhattan Distance in Python (With Examples)

Manhattan Distance is a metric used for measuring the distance between two points in a graph or grid. It is calculated by summing the absolute differences of their Cartesian coordinates. It is also known as the taxicab distance or city block distance, as it is the length of a path a car or taxi would take to get from one location to another. In Python, Manhattan Distance can be easily calculated using the SciPy library, which provides several functions that can be used to calculate this distance. Examples of calculating Manhattan Distance using SciPy are provided below.


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 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

x