Get startedGet started for free

Calculating manhattan distance manually

While euclidean distance is very popular, it only scales well beyond two or three-dimensional data. In these cases, you can use manhattan distance as an alternative. It has the advantage of working exceptionally well with datasets with many categorical features.

Practice calculating it manually with NumPy, which has been loaded under its standard alias np.

This exercise is part of the course

Anomaly Detection in Python

View Course

Exercise instructions

  • Find the absolute differences between the elements of M and N.
  • Find the sum of differences to calculate the final manhattan distance.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

M = np.array([14, 17, 18, 20, 14, 12, 19, 13, 17, 20])
N = np.array([63, 74, 76, 72, 64, 75, 75, 61, 50, 53])

# Subtract M from N and find the absolute value
abs_diffs = ____

# Calculate the final manhattan distance
manhattan_dist_MN = ____

print(manhattan_dist_MN)
Edit and Run Code