How does pandas series div() method work?

PandasServer Side ProgrammingProgramming

In the pandas series constructor, the div() or divide() method is used to perform floating division of two series objects or division of a series with a scalar value. And performs element-wise division operation.

The method returns a series with the result of floating division values. It has 3 parameters, which are fill_value, other, and level. The other parameter is nothing but 2nd input series or a scalar value.

The fill_value parameter is used to fill the missing value. If the index is missed at any one of the series objects, then we can fill that missing index value with a specified value to perform the division operation.

Example 1

import pandas as pd
import numpy as np

# create pandas Series1
series1 = pd.Series([29, 36, 98, 12], index=['A', 'B', 'C', 'D'])

print("First series object:",series1)

# create pandas Series2
series2 = pd.Series([3, 2, 4, 2], index= ['A', 'B', 'D', 'E'])

print("Second series object:",series2)

# divide
print("Divide: ", series1.div(series2))

Explanation

In this example, we will divide the two series object. For that, we created two pandas series by using a list of integers with labeled indices. After that, we applied the divide() method.

Output

First series object:
A 29
B 36
C 98
D 12
dtype: int64

Second series object:
A 3
B 2
D 4
E 2
dtype: int64

Divide:
A 9.666667
B 18.000000
C      NaN
D 3.000000
E      NaN
dtype: float64

We applied the divide() method on two series objects series1 and series2. Based on index labels the division operation is performed between elements of the series. We can see the resultant series object in the above output block.

Example 2

import pandas as pd

# create pandas Series1
series1 = pd.Series([29, 36, 98, 12], index=['A', 'B', 'C', 'D'])

print("First series object:",series1)

# create pandas Series2
series2 = pd.Series([3, 2, 4, 2], index= ['A', 'B', 'D', 'E'])

print("Second series object:",series2)

# divide
print("Divide: ", series1.div(series2, fill_value=10))

Explanation

We created two pandas Series objects like the previous example, but here, we are going to the fill_value parameter with the value “10”. And then applied the divide() method.

Output

First series object:
A 29
B 36
C 98
D 12
dtype: int64

Second series object:
A 3
B 2
D 4
E 2
dtype: int64

Divide:
A  9.666667
B 18.000000
C  9.800000
D  3.000000
E  5.000000
dtype: float64

Here, we successfully performed the floating division between two series objects series1 and series2 with a fill value “10”.

raja
Updated on 09-Mar-2022 09:29:50

Advertisements