DataFrame.dot() method in pandas
Overview
The dot() method is used to compute the dot product between DataFrames or Series. DataFrame.dot() from DataFrame class is used to take the dot product of two DataFrames or DataFrame and Series.
Note: Adot()works like amul()function, but instead of returning multiplication separately, it returns the sum of multiplied values at each row or index.
Syntax
# SignatureDataFrame.dot(other)
Parameters
It takes the following argument value:
other: Another object ofDataFrameorSeriesor array-like to compute dot product.
Return value
It returns either Series or DataFrame.
- If
otherisSeries, it returnsseriesafter simple matrix dot product. - If
otherisDataFrame, it returnsDataFrameafter dot product.
Code
Let's discuss different scenarios with some coding examples. Here we have listed some commonly used cases:
- Only
DataFrames DataFrameandSeries
Only DataFrames
In this code, we'll take two DataFrame of the same dimensions and evaluate their dot product.
# importing pandas module as alias pdimport pandas as pd# Creating a DataFramedf1 = pd.DataFrame([[0, 1, -2, -1],[0, 1, None, 1],[1, 3, 1, -1],[1, 1, 6, 1]])# Creating a DataFramedf2 = pd.DataFrame([[5, 3, 6, 4],[11, 3, 4, 3],[4, 3, 8, 3],[5, None, 2, 8]])# Calculating dot productprint(df1.dot(df2))
Explanation
- Lines 4 to 7: We create a numeric
DataFramedf1that contains fourobservations. Number of rows - Lines 9 to 12: We create a numeric
DataFramedf2that contains four observations. - Line 14: We invoke
df1.dot(df2)to evaluate dot product in return.
DataFrame and Series
In this code snippet, we'll create a pandas DataFrame and Series object to calculate their dot product.
# importing pandas as pdimport pandas as pd# Creating the dataframedf = pd.DataFrame([[5, 3, 6, 4],[11, None, 4, 3],[4, 3, 8, None],[5, 4, 2, 8]])# Creating a seriesseries = pd.Series([1, 1, 2, 1])# Print the dot product between DataFrame and Seriesprint(df.dot(series))
Explanation
- Lines 4 to 7: We create a numeric
DataFramedfthat contains four observations. - Line 9: We instantiate
Seriesto get Pandas series object of four values. - Line 11: We invoke
df.dot(series)to get dot product betweenDataFrameandseries.