8.6 C
London
Friday, December 20, 2024
HomePythonDescriptive Statistics in PythonHow to Calculate Manhattan Distance in Python (With Examples)

How to Calculate Manhattan Distance in Python (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories