How to perform the Integer division operation of a pandas Series by a Python list?


The Integer division operation can also be applied to the elements of pandas Series by another Python sequence like a list or a tuple.

To perform integer division operations we can use the floordiv() method In the pandas series class. Which is used to apply an element-wise integer division operation between a pandas series object by the corresponding element of another Series or a scalar or list-like object.

Here we will discuss some examples to understand how the floordiv() method performs the integer division operation to the elements of a pandas Series by the elements of a Python list.

Example 1

Below is an example to understand the performance of the floordiv() method with regards to the integer division operation.

import pandas as pd
import numpy as np

# create pandas Series
s = pd.Series({'A':None,'B':58,"C":85, "D":28, 'E':np.nan, 'G':60 })

print("Series object:",s)

# apply floordiv() using a list of integers
print("Output:")
print(s.floordiv(other=[18, 16, 9, 15, 14, 6]))

Explanation

Apply the floordiv() function to perform floor division operation of the series object “s” with a python list. The given series object “s” contains some missing values at index positions “A” and “E”.

Output

You will get the following output −

Series object:
A    NaN
B    58.0
C    85.0
D    28.0
E    NaN
G    60.0
dtype: float64

Output:
A    NaN
B    3.0
C    9.0
D    1.0
E    NaN
G    10.0
dtype: float64

In the above output block, the method has successfully returned the result of floor division of the given series object with a python list. And the missing values are still present in the results of the floordiv() method since we haven’t applied any value to the fill_value parameter.

Example 2

For the previous example, here we will apply the integer division operation by replacing missing values using the fill_value parameter.

import pandas as pd
import numpy as np

# create pandas Series
s = pd.Series({'A':None,'B':58,"C":85, "D":28, 'E':np.nan, 'G':60 })

print("Series object:",s)

# apply floordiv() using a list of integers by replacing missing values
print("Output:")
print(s.floordiv(other=[18, 16, 9, 15, 14, 6], fill_value=20))

Output

The output is given below −

Series object:
A    NaN
B    58.0
C    85.0
D    28.0
E    NaN
G    60.0
dtype: float64

Output:
A    1.0
B    3.0
C    9.0
D    1.0
E    1.0
G    10.0
dtype: float64

While executing the above code the missing values are replaced by a scalar value 20 and the output of floor division operation is displayed in the above output block.

Updated on: 07-Mar-2022

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements