Excel to Python: MOD Function - A Complete Guide | Mito
Home Icon
divider

Functions

divider

Math

divider

MOD

How to Use Excel's MOD Function in Pandas

Excel's MOD function returns the remainder after a number is divided. For example, =MOD(10, 3) returns 1, since 10 divided by 3 leaves a remainder of 1.

This page explains how you on can replicate Excel's MOD function in Python using pandas.

To perform modulus operations in Python using pandas, you can use the `%` operator. This works similarly to Excel's MOD function.

The basic modulus operation in pandas is straightforward. For example, in Excel if you wanted to check if a number is even, you could use =MOD(A2, 2).

In pandas, you can use the following code to return 0 if the number is even, and 1 if it's odd.

df['Result'] = df['Column1'] % 2
Copy!
Clipboard

To apply the modulus operation across rows, you can use a second column as the divisor instead of hard-coding a number.

This would be equivalent to using =MOD(A2, B2) in Excel.

df['Result'] = df['Column1'] % df['Column2']
Copy!
Clipboard

Excel has a built-in ISODD function that returns TRUE if a number is odd, and FALSE if it's even. You can replicate this in pandas using the following code:

df['Result'] = df['Column1'] % 2 == 1
Copy!
Clipboard

Excel has a built-in ISEVEN function that returns TRUE if a number is even, and FALSE if it's odd. You can replicate this in pandas using the following code:

df['Result'] = df['Column1'] % 2 == 0
Copy!
Clipboard

When implementing the MOD function in pandas, it's important to be aware of common pitfalls. Here are some to avoid:

Attempting modulus on non-numeric columns will lead to errors. Ensure all columns involved in the operation are numeric. For example, if 'Column1' or 'Column2' contains strings, the code will return an error.

To fix it, convert the columns to numeric first. This will convert any non-numeric values to NaN, which can be handled using fillna(1) so that the result is 0 for any NaN divisors.

# Convert to numeric and fill missing values with 1
df['Column1'] = pd.to_numeric(df['Column1'], errors='coerce').fillna(1)
df['Column2'] = pd.to_numeric(df['Column2'], errors='coerce').fillna(1)

# Perform modulus operation
df['Result'] = df['Column1'] % df['Column2']
Copy!
Clipboard

In Excel, the MOD function takes two arguments: the number to be divided and the divisor.

=MOD(number, divisor)

MOD Excel Syntax

ParameterDescriptionData Type
numberThe number to dividenumber
divisorThe number to divide bynumber

Examples

FormulaDescriptionResult
=MOD(10, 3)Finds the remainder when 10 is divided by 3.1
=MOD(-10, 3)Finds the remainder when -10 is divided by 3.2
=MOD(10, 10)Finds the remainder when 10 is divided by 10.0

Don't re-invent the wheel. Use Excel formulas in Python.

Install Mito

Don't want to re-implement Excel's functionality in Python?

Automate analysis with Mito