We can define Manhattan distance as the sum of the absolute differences of the coordinates between two points in a grid. For example, if we have two points (x1, y1) and (x2, y2), the Manhattan distance would be:
|x1 - x2| + |y1 - y2|

First, let’s start importing Numpy.
import numpy as np
. Computing Manhattan distance between 2D points in Python
Let us compute Manhattan distance between two points shown in the aabove figure illustrating the Manhattan distance.
point1 = np.array([0, 0]) point2 = np.array([4, 4]) print(point1) print(point2)
We first compute the differences between two points.
diff = point1 - point2 diff array([-4, -4])
Then we compute the absolute values of the differences.
abs_diff = np.abs(diff) abs_diff array([4, 4])
Then we add them up to get the Manhattan distance. For the example we have the Manhattan distance is 8.
manhattan_dist = np.sum(abs_diff) manhattan_dist 8
We can use the above steps in a single statement and compute Manhattan distance. For our toy example in the figure, the Manhattan distance is 8 and we can visually verify that as well.
# Calculate the Manhattan distance in 2D manhattan_distance = np.sum(np.abs(point1-point2)) print(manhattan_distance) 8
Here is another example of computing Manhattan distance between two 2D points.
point1 = np.array([1, 2]) point2 = np.array([4, 6])
# Calculate the Manhattan distance in 2D manhattan_distance = np.sum(np.abs(point1-point2)) print(manhattan_distance) 7
<h3. Computing Manhattan distance between two points in 3D
We can use the same approach to compute distance between two points in 2-dimension. For example, the Manhattan distance between two points (x1,y1,z1) and (x2,y2,z2) in 3D is
abs(x1-x2) + abs(y1-y2) + abs(z1-z2)
Let us create some data for points in 3D.
point1 = np.array([1, 2, 3]) point2 = np.array([4, 6, 8])
We can compute Manhattan distance by summing the absolute values of differences between points.
manhattan_distance = np.sum(np.abs(point1-point2)) manhattan_distance 12