Multiplying a DataFrame with another DataFrame, Series or a Python sequence

mul() function of DataFrame does an element-wise multiplication of DataFrame with the elements of a pandas series or with the elements of a Python sequence. The example multiples two DataFrames and prints the results onto the console.

Dataframe Binaryoperatorfunctions Updated 6 Jun 2019 1 min read

Overview

The mul() method of DataFrame object multiplies the elements of a DataFrame object with another DataFrame object, series or any other Python sequence.

mul() does an elementwise multiplication of a DataFrame with another DataFrame, a pandas Series or a Python Sequence.

Calling the mul() method is similar to using the binary multiplication operator(*).

The mul() method provides a parameter fill_value using which values can be passed to replace the np.nan, None values present in the data.

Example

python
import pandas as pd

# Create data

dataSet1 =   [(2, 0, 1, 0),

              (1, 0, 3, 0),

              (4, 3, 2, 0)];

dataSet2 =   [(1, 1, 2, 1),

              (1, 2, 1, 1),

              (3, 1, 1, 3)];

# Construct pandas DataFrame instances

dataFrame1 = pd.DataFrame(data=dataSet1);

dataFrame2 = pd.DataFrame(data=dataSet2);

print("Elements present in DataFrame1:");

print(dataFrame1);

print("Elements present in DataFrame2:");

print(dataFrame2);

# Multiply two DataFrames

multiplicationResults = dataFrame1.mul(dataFrame2);

print("Result of element-wise multiplication of two Data Frames:");

print(multiplicationResults);

Output

Output
Elements present in DataFrame1:

   0  1  2  3

0  2  0  1  0

1  1  0  3  0

2  4  3  2  0

Elements present in DataFrame2:

   0  1  2  3

0  1  1  2  1

1  1  2  1  1

2  3  1  1  3

Result of element-wise multiplication of two Data Frames:

    0  1  2  3

0   2  0  2  0

1   1  0  3  0

2  12  3  2  0