pandas DataFrame.dot() Method Implementations
1. With Series Data
All the multiplied values are then added to get the dot product.
Python3
# Create a DataFrame df = pd.DataFrame({ 'A' : [ 1 , 2 , 3 ], 'B' : [ 4 , 5 , 6 ], 'C' : [ 7 , 8 , 9 ] }) # Create a Series series = pd.Series([ 0.1 , 0.2 , 0.3 ], index = [ 'A' , 'B' , 'C' ]) # Dot product with a Series result_series = df.dot(series) print ( "Dot product with Series:" ) print (result_series) |
Output:
Dot product with Series:
0 3.0
1 3.6
2 4.2
dtype: float64
Explanation:
- Dot product for row 0: 1×0.1+4×0.2+7×0.3=3.01×0.1+4×0.2+7×0.3=3.0
- Dot product for row 1: 2×0.1+5×0.2+8×0.3=3.62×0.1+5×0.2+8×0.3=3.6
- Dot product for row 2: 3×0.1+6×0.2+9×0.3=4.23×0.1+6×0.2+9×0.3=4.2
2. With Dataframe
Python3
# Creating a DataFrame df1 df1 = pd.DataFrame([[ 0 , 1 , - 9 , 1 ], [ 9 , 1 , 0 , 1 ], [ 1 , 3 , 1 , - 1 ], [ 1 , 1 , 8 , 1 ]]) # Creating another DataFrame df2 df2 = pd.DataFrame([[ 5 , 3 , 7 , 4 ], [ 1 , 3 , 4 , 3 ], [ 4 , 3 , 8 , 6 ], [ 5 , 8 , 2 , 8 ]]) # Calculating dot product result = df1.dot(df2) # Printing the result print (result) |
Output:
0 1 2 3
0 -30 -16 -66 -43
1 51 38 69 47
2 7 7 25 11
3 43 38 77 63
Explanation:
- Each row in the resulting DataFrame represents the dot product of the corresponding row in
df1
and the columns indf2
. - For example, the first row (row 0) is calculated as follows:
- 0×5+1×3+(−9)×7+1×4=−300×5+1×3+(−9)×7+1×4=−30
- 0×1+1×3+(−9)×3+1×8=−160×1+1×3+(−9)×3+1×8=−16
- 0×4+1×3+(−9)×8+1×2=−660×4+1×3+(−9)×8+1×2=−66
- 0×5+1×8+(−9)×2+1×8=−430×5+1×8+(−9)×2+1×8=−43
- The same logic is applied to calculate each element in the resulting DataFrame.
3. With Numpy Array
Python3
# Creating a DataFrame df1 df1 = pd.DataFrame([[ 0 , 1 , - 9 , 1 ], [ 9 , 1 , 0 , 1 ], [ 1 , 3 , 1 , - 1 ], [ 1 , 1 , 8 , 1 ]]) # Creating a NumPy array numpy_array = np.array([ 5 , 3 , 7 , 4 ]) # Calculating dot product with NumPy array result = df1.dot(numpy_array) # Printing the result print (result) |
Output:
0 -56
1 52
2 17
3 68
dtype: int64
Explanation:
Each row represents the dot product of the corresponding row in the original DataFrame df1
with the NumPy array numpy_array.
- For the first row: 0 * 5 + 1 * 3 + (-9) * 7 + 1 * 4 = -56
- For the second row: 9 * 5 + 1 * 3 + 0 * 7 + 1 * 4 = 52
- For the third row: 1 * 5 + 3 * 3 + 1 * 7 + (-1) * 4 = 17
- For the fourth row: 1 * 5 + 1 * 3 + 8 * 7 + 1 * 4 = 68
Contact Us