Home Â» How to Calculate Dot Product Using NumPy

# How to Calculate Dot Product Using NumPy

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

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

For example, if a = [2, 5, 6] and b = [4, 3, 2], then the dot product of a and b would be equal to:

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

a Â· b =Â 8 + 15 + 12

a Â· b =Â 35

Simply put, the dot productÂ is the sum of the products of the corresponding entries in two vectors.

In Python, you can use the numpy.dot() function to quickly calculate the dot product between two vectors:

```import numpy as np

np.dot(a, b)
```

The following examples show how to use this function in practice.

### Example 1: Calculate Dot Product Between Two Vectors

The following code shows how to use numpy.dot() to calculate the dot product between two vectors:

```import numpy as np

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

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

33
```

Here is how this value was calculated:

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

### Example 2: Calculate Dot Product Between Two Columns

The following code shows how to use numpy.dot() to calculate the dot product between two columns in a pandas DataFrame:

```import pandas as pd
import numpy as np

#create 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 is how this value was calculated:

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

Note: Keep in mind that Python will throw an error if the two vectors youâ€™re calculating the dot product for have different lengths.