What is the DataFrame.mul() method in Python?
Overview
In Python, the DataFrame.mul() method is used to perform multiplication operations on DataFrame objects. It is an element-wise binary operation, while multiplication is denoted with an asterisk (*) operator. It also provides an additional feature to handle the DataFrame objects.
Syntax
# SignatureDataFrame.mul(other, axis = 'columns', level = None, fill_value = None)
Parameters
It takes four parameters:
other: This is a single or multiple element data structure or list-like object. It can be aDataFrame, series, sequence, scalar, or a constant.axis: This is used for deciding the axis on which the operation is applied. Whether to compare by the index (0orindex) or columns (1orcolumns) that is{0 or 'index', 1 or 'columns'}.level: This broadcasts across a level and matchesIndexvalues on the passed multi-indexlevel. The level could be a number or a label that marks the point at which two things have to be compared. So, it could be either an integer or a label.
fill_value: This is used to fill missing values which are represented asNaNin theDataFrame. If we assign a number, let's sayxusingfill_value = x, all the missing values in the result will be filled withx.
Return value
It returns a DataFrame obtained as a result of the arithmetic operation that is the mul() operator. In our case, we use *. As a result, we obtain answers obtained by the multiplication of the DataFrame objects.
Explanation
The first thing for implementation is to import pandas. Here, we import pandas as pd. So, pd will be used in place of pandas in the entire program.
Scalar multiplication with any DataFrame
Consider we have a DataFrame object, df, containing dictionaries where country names are the keys having some values. We apply pandas DataFrame multiplication method as follows:
# importing pandas as pdimport pandas as pd# Creating a dataframe with five observationsdf= pd.DataFrame({"England":[14,4,5,4,1],"Pakistan":[5,2,54,3,2],"Australia":[20,20,7,3,8],"Westindies":[14,3,6,2,6]})# Print the dataframeprint(df)print()print(df.mul(2, axis = 0))
Explanation
- Line 4–7: We create a
DataFramecontaining nameddfhaving countries names as key values for dictionary. - Line 9: We print the
DataFrame. - Line 12: We apply the
mul()method as required on theDataFrameand print the result.
Multiplication of two DataFrames
- Line 4–7: We create
df1having countries names as key values for dictionary. - Line 10: We print the
DataFrameobject,df1. - Line 13–16: We create
df2having countries names as key values for dictionary. - Line 19: We print the
DataFrameobject,df2. - Line 23: We apply the pandas
mul()method for multiplication of bothDataFrameobjects and print results.
Hence, we can use this method in different ways just by changing the parameters.