Pandas DataFrame | rmod method
Start your free 7-days trial now!
Pandas DataFrame.rmod(~)
method computes the modulo of the values in the source DataFrame and another scalar, sequence, Series or DataFrame, that is:
other % DataFrame
Note that this is just the reverse of DataFrame.mod(~)
, which does:
DataFrame % other
Unless you use the parameters axis
, level
and fill_value
, rmod(~)
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 other
to 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 match up. 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 pair of entries are NaN
, then its result would also be NaN
. By default, fill_value=None
.
Return Value
A new DataFrame computed by the modulo.
Examples
Basic usage
Consider the following DataFrames:
df = pd.DataFrame({"A":[2,3], "B":[4,5]}) df_other = pd.DataFrame({"A":[9,8], "B":[7,6]})
A B | A B0 2 4 | 0 9 71 3 5 | 1 8 6
Computing the modulo:
df.rmod(df_other)
A B0 1 31 2 1
Here, we're computing the following element-wise modulo:
9%2 7%48%3 6%5
Note that this is equivalent to:
df_other % df
A B0 1 31 2 1
Broadcasting
Consider the following DataFrame:
df = pd.DataFrame({"A":[3,4], "B":[5,6]})df
A B0 3 51 4 6
Row-wise modulo
By default, axis=1
, which means that other
will be broadcasted for each row in df
:
df.rmod([8,9]) # axis=1
A B0 2 41 0 3
Here, we're computing the following element-wise modulo:
8%3 9%58%4 9%6
Column-wise modulo
To broadcast other
for each column in df
, set axis=0
like so:
df.rmod([8,9], axis=0)
A B0 2 31 1 3
Here, we're computing the following element-wise modulo:
8%3 8%59%4 9%6
Specifying fill_value
Consider the following DataFrame:
df = pd.DataFrame({"A":[2,np.NaN], "B":[np.NaN,3]})df_other = pd.DataFrame({"A":[8,9],"B":[np.NaN,np.NaN]})
A B | A B0 2.0 NaN | 0 8 NaN1 NaN 3.0 | 1 9 NaN
By default, when we compute the modulo using rmod(~)
, any operation with NaN
results in NaN
:
df.rmod(df_other)
A B0 0.0 NaN1 NaN NaN
We can fill the NaN
values before we compute the modulo by using the fill_value
parameter:
df.rmod(df_other, fill_value=5)
A B0 0.0 NaN1 4.0 2.0
Here, notice how when the operation involves two NaN
, then the resulting modulo would still be NaN
, regardless of fill_value
.