Monday, September 23, 2024
Google search engine
HomeLanguagesPython | Pandas Dataframe/Series.dot()

Python | Pandas Dataframe/Series.dot()

Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. 

Pandas Series dot()

Pandas Series.dot() works similarly to pd.mul() method, but instead of returning multiplied separate values, the Dot product is returned (Sum of multiplication of values at each index).

Pandas Series dot() Syntax

Syntax: Series.dot(other)

Parameters:

  • other: Other Series to be used to calculate DOT product

Return type: Series with updated values

Pandas Series dot() Method

In this example, two series are created from Python lists using Pandas Series() method. The method is then called on series1 and series2 is passed as a parameter. The result is then stored in a variable and displayed.

Python3




# importing pandas module
import pandas as pd
     
# importing numpy module
import numpy as np
     
# creating series 1
series1 = pd.Series([7, 5, 6, 4, 9])
     
# creating series 2
series2 = pd.Series([1, 2, 3, 10, 2])
 
# storing in new variable
# calling .dot() method
ans = series1.dot(series2)
 
# display
print('Dot product = {}'.format(ans))


Output:

Dot product = 93

Deep Code Explanation

The elements in the caller series are multiplied by the element at the same index in the past series. All the multiplied values are then added to get the dot product. As in the above example, the series are:

[7, 5, 6, 4, 9]
[1, 2, 3, 10, 2]

Dot product = 7*1 + 5*2 + 6*3 + 4*10 + 9*2 = 7 + 10 + 18 + 40 + 18 = 93

Note: If there is any Null value in any of the series, the net result is NaN. NaN values should be removed/replaced using dropna() or fillna() methods respectively. 

Pandas Dataframe dot() 

We can also use Pandas Dataframe for using the dot() method. The dot() method multiplies each value from one DataFrame with the values from another DataFrame, and adds them together.

Pandas Dataframe dot() Syntax

Syntax: dataframe.dot(other)

Parameters:

  • other: Other Dataframe to be used to calculate DOT product

Return type: Dataframe with updated values

Example

All the multiplied values are then added to get the dot product. 

Python3




# import DataFrame
import pandas as pd
 
# using DataFrame.dot() method
gfg1 = pd.DataFrame([[1, 4], [9, 5]])
gfg2 = pd.DataFrame([[4, 3, 2, 1], [21, -3, -4, 1]])
 
print(gfg1.dot(gfg2))


Output:

     0   1   2   3
0   88  -9 -14   5
1  141  12  -2  14

RELATED ARTICLES

Most Popular

Recent Comments