2 Upvotes
Calculating the Distance Between Two Vectors With Numpy
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.
import numpy as np vectors = vectors.toarray() #Calculate distance using Numpy linalg distance = np.linalg.norm(vectors[1]-vectors[0]) #Calculate distance from scratch distance = 0 for i in range(0, len(vectors[0])): d = (vectors[1][i] - vectors[0][i]) ** 2 distance += d distance = distance**(1/2)
By detro - Last Updated Jan. 13, 2022, 10:16 a.m.
COMMENTS
RELATED SNIPPETS
3
1
How to Perform Stratified Sampling Using Pandas
Python
Statistics & Probability
1
1
1
Find Snippets by Language
Find Snippets by Use