# Calculating the Distance Between Two Vectors With Numpy

Python
Statistics & Probability

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.

Did you find this snippet useful?

RELATED SNIPPETS
Get z-score for a column and add to Datafame
Python
Statistics & Probability
3
How to Calculate a Factorial Using Python
Python
Statistics & Probability
1
How to Perform Stratified Sampling Using Pandas
Python
Statistics & Probability
1
How to Calculate the Sampling Error
Python
Statistics & Probability
1
Numpy Descriptive Statistics
Python
Statistics & Probability

1
Top Contributors
103
100
Find Snippets by Language
Find Snippets by Use