How to use the DataFrame.mod() method in pandas
Overview
The DataFrame.mod() method from the pandas module is used to calculate the element-wise modulus (binary operator mod) of two DataFrames, Series, or Constants.
Note: We can also modulo operator%instead. However, it does not deal withfields. empty NaN values
Syntax
DataFrame.mod(other, axis='columns', level=None, fill_value=None)
DataFrame.mod() Syntax
Parameters
It takes the following argument values:
other: This can be a DataFrame, Series, or Constant.axis: This can be0 or indexor1 or columns. Its default value is'columns'.level: The broadcast value across a level can either beintorNone. Its default value isNone.
fill_value: This can either be afloatvalue orNone. Its default value isNone.
Return value
It returns a DataFrame containing modulo results.
Explanation
In the code snippet below, we'll calculate the modulus of:
-
and argument constant value.DataFrame object Callee object - DataFrame object and argument DataFrame object.
- DataFrame object and argument Series object.
# importing Pandas and Numpyimport pandas as pdimport numpy as np# Creating a DataFramedf1= pd.DataFrame([[5, 3, 6, 4],[11, None, 4, 3],[4, 3, 8, None],[5, 4, 2, 8]])# Creating another DataFramedf2= pd.DataFrame([[None, 4, 5, 9],[1, None, 4, 3],[14, 3, -1, None],[2, 14, 8, 8]])# Creating Numpy arraydata = np.array([6, 12, -3, 9])# Converting to Python seriesseries = pd.Series(data)"""DataFrame and Constant"""# Invoking mod() method# Evaluating modulus between df1 and constantmodulus= df1.mod(3, fill_value = 2)# print resultsprint("DataFrame and Constant")print(modulus)"""Both are DataFrames"""# Evaluating modulus between df1 and df2modulus= df1.mod(df2, fill_value = 2)print("\nBoth are DataFrames")print(modulus)"""DataFrame and Series"""# Evaluating modulus between df1 and seriesmodulus= df1.mod(series)print("\nDataFrame and Series")print(modulus)
Explanation
- Lines 5 to 13: We create two numeric DataFrames, each containing four rows and four columns.
- Lines 15 to 17: We create a pandas series of
4values. - Line 22: We calculate the modulus of
df1object and the argument constant value. - Line 29: We calculate the modulus of
df1object and the argument DataFramedf2object. - Line 35: We calculate the modulus of
df1object and the argumentseriesobject.