Pandas DataFrame | rmul method
Start your free 7-days trial now!
Pandas DataFrame.rmul(~)
method multiplies a scalar, sequence, Series or DataFrame to the values in the source DataFrame, that is:
other * DataFrame
Note that this is the reverse of DataFrame.mul(~)
, which does the following:
DataFrame * other
Unless you use the parameters axis
, level
and fill_value
, rmul(~)
is equivalent to performing multiplication using the *
operator.
Parameters
1. other
link | scalar
or sequence
or Series
or DataFrame
The resulting DataFrame will be other
multiplied with the source DataFrame.
2. axis
link | int
or string
| optional
Whether to broadcast other
for each column or row of the source DataFrame:
Axis | Description |
---|---|
|
|
|
|
This is only relevant if the shape of the source DataFrame and that of other
does not align. By default, axis=1
.
3. level
| int
or string
| optional
The name or the integer index of the level to consider. This is only relevant if your DataFrame is Multi-index.
4. fill_value
link | float
or None
| optional
The value to replace NaN
before the computation. If both entries are NaN
, then the resulting product would always be NaN
. By default, fill_value=None
.
Return value
A new DataFrame resulting from the product of the source DataFrame and other
.
Examples
Basic usage
Consider the following DataFrames:
df = pd.DataFrame({"A":[2,3], "B":[4,5]})df_other = pd.DataFrame({"A":[6,7], "B":[8,9]})
A B | A B0 2 4 | 0 6 81 3 5 | 1 7 9
Computing their product yields:
df.rmul(df_other)
A B0 12 321 21 45
Note that this is equivalent to the following:
df_other * df
A B0 12 321 21 45
Broadcasting
Consider the following DataFrame:
df = pd.DataFrame({"A":[2,3], "B":[4,5]})df
A B0 2 41 3 5
Row-wise multiplication
By default, axis=1
, which means that other
will be broadcasted for each row in df
:
df.rmul([10,100]) # axis=1
A B0 20 4001 30 500
Here, we're doing the following element-wise multiplication:
10*2 100*410*3 100*5
Column-wise multiplication
To broadcast other
for each column in df
, set axis=0
like so:
df.mul([10,100], axis=0)
A B0 20 401 300 500
Here, we're doing the following element-wise multiplication:
10*2 10*4100*3 100*5
Specifying fill_value
Consider the following DataFrames with missing values:
df = pd.DataFrame({"A":[2,np.NaN], "B":[np.NaN,5]})df_other = pd.DataFrame({"A":[10,20],"B":[np.NaN,np.NaN]})
A B | A B0 2.0 NaN | 0 10 NaN1 NaN 5.0 | 1 20 NaN
By default, when we compute the product using rmul(~)
, any operation with NaN
results in NaN
:
df.rmul(df_other)
A B0 20.0 NaN1 NaN NaN
We can fill the NaN
values before we perform multiplication by using the fill_value
parameter:
df.rmul(df_other, fill_value=100)
A B0 20.0 NaN1 2000.0 500.0
Notice how the product of two NaN
is NaN
, regardless of fill_value
.