Matrix Multiplication of DataFrames
To compute the matrix multiplication between the DataFrame and other DataFrame, call dot() method on this DataFrame and pass the other object as argument to this method.
In this tutorial, we will learn the syntax of DataFrame.dot() method and how to use this method to compute matrix multiplication of DataFrame with other.
Syntax
The syntax of pandas DataFrame.dot() method is
DataFrame.dot(other)
where
Parameter | Value | Description |
---|---|---|
other | Series, DataFrame or array-like | The other object to compute the matrix product with. |
Return Value
If other object is a DataFrame or a numpy.array, return the matrix product of self and other in a DataFrame of a np.array.
Notes
The dimensions of DataFrame and other must be compatible in order to compute the matrix multiplication.
Also, the column names of DataFrame and the index of other must contain the same values, as they will be aligned prior to the multiplication.
Examples
Matrix Multiplication of Two DataFrames
In the following program, we take two DataFrames and compute their matrix multiplication using DataFrame.dot() method.
Example.py
import pandas as pd
df = pd.DataFrame([[1, 2], [3, 4]])
other = pd.DataFrame([[1, 0], [2, 1]])
result = df.dot(other)
print(result)
Output
0 1
0 5 2
1 11 4
DataFrames Must be Aligned for Matrix Multiplication
The columns of this DataFrame must align with the index of other DataFrame for computing matrix multiplication.
In the following program, we take two DataFrames in df
and other
. Then, prior to matrix multiplication, we align the two DataFrames by assigning the index of other DataFrame with the columns of this DataFrame.
Example.py
import pandas as pd
df = pd.DataFrame({'a': [1, 4], 'b': [3, 4]})
other = pd.DataFrame({'c': [1, -1], 'd': [2, 1]})
other.index = df.columns
result = df.dot(other)
print(result)
Output
c d
0 -2 5
1 0 12
If the DataFrames are not aligned prior to matrix multiplication, then ValueError is raised.
Example.py
import pandas as pd
df = pd.DataFrame({'a': [1, 4], 'b': [3, 4]})
other = pd.DataFrame({'c': [1, -1], 'd': [2, 1]})
result = df.dot(other)
print(result)
Output
ValueError: matrices are not aligned
Conclusion
In this Pandas Tutorial, we learned how to compute matrix multiplication of two DataFrames using pandas DataFrame.dot() method.