Pandas DataFrame mod() method with examples

Spread the love

The mod() method finds the modulo (remainder) of each value in the DataFrame when you divide them by a specified value. This is equivalent to dataframe % other, but with support to substitute a fill_value for missing data in one of the inputs.

Syntax –

DataFrame.mod(other, axis='columns', level=None, fill_value=None)

other – Any single or multiple element data structure, or list-like object.

axis – Whether to compare by the index (0 or ‘index’) or columns (1 or ‘columns’). For Series input, axis to match Series index on.

level – Broadcast across a level, matching Index values on the passed MultiIndex level.

fill_value – Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Examples –

Let’s create a dataframe to work with.

import pandas as pd
import numpy as np

df = pd.DataFrame({'A':[1, 2, 3, 4, 5, np.nan],
                 'B':[6, 7, 8, 9, 10, np.nan]})

1 . Dividing by a value –

Let’s say you want to divide each values in the dataframe by 2 and find the remainder. One way of doing this is

df % 2

Another way to do this is using the mod() method in pandas.


2. Fill missing values then divide –

If you look at the dataframe, you can see that it contains some missing values. We can first fill these missing values using the fill_value parameter and then do the division to find the remainder.

df.mod(2, fill_value=5)

3 . Dividing by a series –

You can also divide the dataframe by a pandas series.

# create a series
s1 = pd.Series([1, 2, 3, 4, 5, np.nan])

# divide the dataframe by this series
df.mod(s1, axis=0)

Rating: 1 out of 5.

Leave a Reply