logo_learn_stats

The best way to Calculate Dot Product The use of NumPy

Posted on
banner 336x280

Given vector a = [a1, a2, a3] and vector b = [b1, b2, b3], the dot product of the vectors, denoted as a · b, is given through:

a · b = a1 * b1 + a2 * b2 + a3 * b3

banner 468x60

For instance, if a = [2, 5, 6] and b = [4, 3, 2], upcoming the dot made from a and b could be equivalent to:

a · b = 2*4 + 5*3 + 6*2

a · b = 8 + 15 + 12

a · b = 35

Merely put, the dot product is the sum of the goods of the corresponding entries in two vectors.

In Python, you’ll significance the numpy.dot() serve as to temporarily calculate the dot product between two vectors:

import numpy as np

np.dot(a, b)

Please see examples display the best way to significance this serve as in follow.

Instance 1: Calculate Dot Product Between Two Vectors

Please see code presentations the best way to significance numpy.dot() to calculate the dot product between two vectors:

import numpy as np

#outline vectors
a = [7, 2, 2]
b = [1, 4, 9]

#calculate dot product between vectors
np.dot(a, b)

33

Here’s how this worth used to be calculated:

  • a · b = 7*1 + 2*4 + 2*9
  • a · b = 7 + 8 + 18
  • a · b = 33

Instance 2: Calculate Dot Product Between Two Columns

Please see code presentations the best way to significance numpy.dot() to calculate the dot product between two columns in a pandas DataFrame:

import pandas as pd
import numpy as np

#form DataFrame
df = pd.DataFrame({'A': [4, 6, 7, 7, 9],
                   'B': [5, 7, 7, 2, 2],
                   'C': [11, 8, 9, 6, 1]})

#view DataFrame
df

	A	B	C
0	4	5	11
1	6	7	8
2	7	7	9
3	7	2	6
4	9	2	1

#calculate dot product between column A and column C
np.dot(df.A, df.C)

206

Here’s how this worth used to be calculated:

  • A · C = 4*11 + 6*8 + 7*9 + 7*6 + 9*1
  • A · C = 44 + 48 + 63 + 42 + 9
  • A · C = 206

Word: Stock in thoughts that Python will throw an error if the 2 vectors you’re calculating the dot product for have other lengths.

Spare Sources

The best way to Upload Rows to a Pandas DataFrame
The best way to Upload a Numpy Array to a Pandas DataFrame
The best way to Calculate Rolling Correlation in Pandas

banner 336x280

Leave a Reply

Your email address will not be published. Required fields are marked *