Calculating the Distance Between Two Vectors With Numpy

Python

In this example we have a dataframe called vectors where each row is a vector. First we convert to a numpy array and then calculate the distance between the first two vectors in the data.

In the first example we use linalg.norm in Numpy to calculate the distance and then in the second we calculate from scratch using a for loop. These two methods are equivalent.

 1|  import numpy as np
 2|  
 3|  vectors = vectors.toarray()
 4|  
 5|  #Calculate distance using Numpy linalg
 6|  distance = np.linalg.norm(vectors[1]-vectors[0])
 7|  
 8|  #Calculate distance from scratch
 9|  distance = 0
10|  for i in range(0, len(vectors[0])):
11|  	d = (vectors[1][i] - vectors[0][i]) ** 2
12|  	distance += d
13|  distance = distance**(1/2)
14|  
15|  
Did you find this snippet useful?

Sign up for free to to add this to your code library