Pandas DataFrame | mod method
Start your free 7-days trial now!
Pandas DataFrame.mod(~)
method computes the modulo of the values in the source DataFrame and another scalar, sequence, Series or DataFrame, that is:
DataFrame % other
Unless you use the parameters axis
, level
and fill_value
, mod(~)
is equivalent to computing the modulo using the %
operator.
Parameters
1. other
link | scalar
or sequence
or Series
or DataFrame
The resulting DataFrame will be the modulo of the source DataFrame and other
.
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 relevant only if your DataFrame is Multi-index.
4. fill_value
link | float
or None
| optional
The value to replace NaN
before the computation of the modulo. If both the entries in the source DataFrame and the other are NaN
, then the result for that entry will still be NaN
. By default, fill_value=None
.
Return Value
A new DataFrame
computed by the modulo of the source DataFrame and other
.
Examples
Basic usage
Consider the following DataFrames:
df = pd.DataFrame({"A":[12,13], "B":[24,25]})df_other = pd.DataFrame({"A":[4,5], "B":[7,8]})
A B | A B0 12 24 | 0 4 71 13 25 | 1 5 8
Computing the modulo:
df.mod(df_other)
A B0 0 31 3 1
Note that this is equivalent to:
df % df_other
A B0 0 31 3 1
Broadcasting
Consider the following DataFrame:
df = pd.DataFrame({"A":[12,13], "B":[24,25]})df
A B0 12 241 13 25
Row-wise addition
By default, axis=1
, which means that other
will be broadcasted for each row in df
:
df.mod([10,20]) # axis=1
A B0 2 41 3 5
Here, we're computing the following element-wise modulo:
12%10 24%2013%10 25%20
Column-wise addition
To broadcast other
for each column in df
, set axis=0
like so:
df.mod([10,20], axis=0)
A B0 2 41 13 5
Here, we're computing the following element-wise modulo:
12%10 24%1013%20 25%20
Specifying fill_value
Consider the following DataFrames:
df = pd.DataFrame({"A":[12,np.NaN], "B":[np.NaN,25]})df_other = pd.DataFrame({"A":[10,20],"B":[np.NaN,np.NaN]})
A B | A B0 12.0 NaN | 0 10 NaN1 NaN 25.0 | 1 20 NaN
By default, when we compute the modulo using mod(~)
, any operation with NaN
results in NaN
:
df.mod(df_other)
A B0 2.0 NaN1 NaN NaN
We can fill the NaN
values before we compute the modulo by using the fill_value
parameter:
df.mod(df_other, fill_value=5)
A B0 2.0 NaN1 5.0 0.0
Notice how the operation between two NaN
still results in a NaN
, regardless of fill_value
.