How to find the dot product of two pandas series objects?

PandasServer Side ProgrammingProgramming

The series.dot() method in pandas series is used to perform the dot product operation of two pandas series objects. In mathematics, a dot product of two sequences is given by Sum of multiplication of values at each sequence.

The series.dot() takes only one parameter which is another object, it takes a series or an array-like object to perform dot product between elements of each object.

Example 1

# import pandas packages
import pandas as pd

# Creating Series objects

series1 = pd.Series([1, 0, 5, 2])
print('First series object:',series1)

series2 = pd.Series([3, 7, 2, 9])
print('second series object:',series2)

print("Dot product of Series1 and Series2:", series1.dot(series2))

Explanation

Initially, we created two pandas Series objects using a python list of integer values. And then applied the dot product between elements of two series objects series1 and series2.

Output

First series object:
0 1
1 0
2 5
3 2
dtype: int64
second series object:
0 3
1 7
2 2
3 9
dtype: int64

Dot product of Series1 and Series2: 31

The dot product of the given example is 31, the given series objects are the same number of elements with the same index labels. If the labels of two series objects are different then it will raise an error. So that we must give the same index labels for both series objects.

Example 2

# import pandas packages
import pandas as pd

# Creating Series objects

series1 = pd.Series([71, 53, 84, 10], index=['A', 'B', 'C', 'D'])
print('First series object:',series1)

series2 = pd.Series([9, 27, 42, 38], index=['A', 'B', 'C', 'D'])
print('second series object:',series2)

print("Dot product of Series1 and Series2:", series1.dot(series2))

Explanation

Initially, we have created two pandas Series objects with specific index labels. After that, we applied the dot product between those two series objects.

Output

First series object:
A 71
B 53
C 84
D 10
dtype: int64

second series object:
A  9
B 27
C 42
D 38
dtype: int64

Dot product of Series1 and Series2: 5978

The series.dot() method returns a value, which denotes the dot product of the two series objects. For the following example, the dot product value is “5978”.

raja
Updated on 09-Mar-2022 09:34:21

Advertisements