Pandas DataFrame | div method
Start your free 7-days trial now!
Pandas DataFrame.div(~)
method divides the values in the source DataFrame by a scalar, sequence, Series or DataFrame, that is:
DataFrame / other
Unless you use the parameters axis
, level
and fill_value
, div(~)
is equivalent to performing division using the /
operator.
Parameters
1. other
link | scalar
or sequence
or Series
or DataFrame
The resulting DataFrame will be the source DataFrame divided by other
.
2. axis
link | int
or string
| optional
Whether to broadcast other
for each column or row of the source DataFrame:
Axis | Description |
---|---|
|
|
|
|
axis
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 relevant only if your DataFrame is Multi-index.
4. fill_value
link | float
or None
| optional
The value to replace NaN
before the computation. Division between two NaN
will still result in NaN
. By default, fill_value=None
.
Return Value
A new DataFrame
resulting from the division.
Examples
Basic usage
Consider the following DataFrames:
df = pd.DataFrame({"A":[20,30], "B":[40,50]})df_other = pd.DataFrame({"A":[5,6], "B":[4,25]})
A B | A B0 20 40 | 0 5 41 30 50 | 1 6 25
Performing division yields:
df.div(df_other)
A B0 4.0 10.01 5.0 2.0
Note that this is equivalent to:
df / df_other
A B0 4.0 10.01 5.0 2.0
Broadcasting
Consider the following DataFrame:
df = pd.DataFrame({"A":[20,30], "B":[40,50]})df
A B0 20 401 30 50
Row-wise division
By default, axis=1
, which means that other
will be broadcasted for each row in df
:
df.div([10,100]) # axis=1
A B0 2.0 0.41 3.0 0.5
Here, we're doing the following element-wise division:
20/10 40/10030/10 50/100
Column-wise division
To broadcast other
for each column in df
, set axis=0
like so:
df.div([10,100], axis=0)
A B0 2.0 4.01 0.3 0.5
Here, we're doing the following element-wise division:
20/10 40/1030/100 50/100
Specifying fill_value
Consider the following DataFrame:
By default, when we compute the division using div(~)
, any operation with NaN
results in NaN
:
df.div(df_other)
A B0 0.2 NaN1 NaN NaN
We can fill the NaN
values before we perform division by using the fill_value
parameter like so:
df.div(df_other, fill_value=100)
A B0 0.2 NaN1 5.0 0.05
Notice when the operation is between two NaN
, its result would still be NaN
, regardless of fill_value
.