Overview
- The function Series.mod() performs a modulo division of values of a pandas.Series instance by another Series. The modulo division returns only the remainder from the division operation.
- Calling Series.mod() function is similar to using the modulo division operator “%”. However using the Series.mod() function enables replacing None, NaN using the fill_value parameter.
- In the same way, to perform floor division or integer division of one pandas.Series instance by another Series the Series.floordiv() can be used.
- As apposed to modulo division operation the floor division returns only the quotient of the division operation.
Example
# Example Python program to perform modulo division of a pandas.Series
# by another Series
import pandas as pds
firstSeries = pds.Series([13, 25, 37, 49, 57]);
secondSeries = pds.Series([2, 4, 6, 5, 10]);
remainders = firstSeries.mod(secondSeries);
print("Contents of the first series:");
print(firstSeries);
print("Contents of the second series:");
print(secondSeries);
print("First series modulo divided by the second series:");
print(remainders);Output
Contents of the first series:
0 13
1 25
2 37
3 49
4 57
dtype: int64
Contents of the second series:
0 2
1 4
2 6
3 5
4 10
dtype: int64
First series modulo divided by the second series:
0 1
1 1
2 1
3 4
4 7
dtype: int64Example – Modulo division of one pandas Series by a Python Sequence
A pandas Series can be modulo divided by any Python sequence. This example uses a Python tuple to perform a modulo division on a pandas Series.
# Example Python program to perform modulo division of a pandas.Series
# by another Python Sequence
import pandas as pds
series1 = pds.Series([2, 22, 3, 33, 4, 44]);
pythonSequence = (2, 3, 4, 5, 6, 7);
theRemainders = series1.mod(pythonSequence);
print("Contents of series1:");
print(series1);
print("Contents of the Python Seuqence:");
print(pythonSequence);
print("Series1 modulo divided by the Python Seuqence:");
print(theRemainders);Output
Contents of series1:
0 2
1 22
2 3
3 33
4 4
5 44
dtype: int64
Contents of the Python Seuqence:
(2, 3, 4, 5, 6, 7)
Series1 modulo divided by the Python Seuqence:
0 0
1 1
2 3
3 3
4 4
5 2
dtype: int64Example – Performing modulo division of one pandas Series by another while filling Nan/None values with a default value
# Example Python program to perform modulo division of a pandas.Series
# by another while filling None/NaN with default values
import pandas as pds
# Create python lists
list1 = [6, 11, 17, 21, 28];
list2 = [1, 11, None, 4, 5];
# Create pandas Series objects from Python lists
s1 = pds.Series(list1);
s2 = pds.Series(list2);
# Perform modulo division
s3 = s1.mod(s2, fill_value=10);
print(s1);
print(s2);
print(s3);Output
0 6
1 11
2 17
3 21
4 28
dtype: int64
0 1.0
1 11.0
2 NaN
3 4.0
4 5.0
dtype: float64
0 0.0
1 0.0
2 7.0
3 1.0
4 3.0
dtype: float64