Signup/Sign In
PUBLISHED ON: MARCH 16, 2021

Pandas DataFrame div() Method

In this tutorial, we will learn the Python pandas DataFrame.div() method. It returns a floating division of dataframe and other, element-wise (binary operator truediv). It returns a DataFrame with the result of the arithmetic operation.

The below shows the syntax of the python pandas DataFrame.div() method.

Syntax

DataFrame.div(other, axis='columns', level=None, fill_value=None)

Parameters

other: scalar, sequence, Series, or DataFrame. Any single or multiple element data structure, or list-like object.

axis:{0 or ‘index’, 1 or ‘columns’}. Whether to compare by the index (0 or ‘index’) or columns (1 or ‘columns’). For Series input, axis to match Series index on.

level: int or label. Broadcast across a level, matching Index values on the passed MultiIndex level.

fill_value: float or None, default None. Fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment, with this value before computation. If data in both corresponding DataFrame locations is missing the result will be missing.

Example 1: Divide DataFrame by using DataFrame.div() Method

The below example shows the dividing of DataFrame by constant using the DataFrame.div() method.

#importing pandas as pd
import pandas as pd
#creating DataFrame
df1 = pd.DataFrame({'a': [2, 5, 6],'b': [8, 10, 12],'c': [14, 16, 18]})
print(df1.div(3))

Once we run the program we will get the following output.


a b c
0 0.666667 2.666667 4.666667
1 1.666667 3.333333 5.333333
2 2.000000 4.000000 6.000000

Example 2: Divide DataFrame by using DataFrame.div() Method

The below example shows the dividing of DataFrame with other dataframe using the DataFrame.div() method.

import pandas as pd
df1 = pd.DataFrame({'a': [2, 5, 6],'b': [8, 10, 12],'c': [14, 16, 18]})
df2 = pd.DataFrame({'a': [2, 2, 2],'b': [2, 2, 2],'c': [2, 2, 2]})
print(df1.div(df2))

Once we run the program we will get the following output.


a b c
0 1.0 4.0 7.0
1 2.5 5.0 8.0
2 3.0 6.0 9.0

Example 3: Divide DataFrame by using DataFrame.div() Method and filling null values

The below example shows the dividing of DataFrame with other using the DataFrame.div() method with fill_value=1.

import pandas as pd
df1 = pd.DataFrame({'a': [2, 5, 6],'b': [8, 10, 12],'c': [14, 16, 18]})
df2 = pd.DataFrame({'a': [2, 2, 2],'b': [2, 2, 2]})
print(df1.div(df2,fill_value=1))

Once we run the program we will get the following output.


a b c
0 1.0 4.0 14.0
1 2.5 5.0 16.0
2 3.0 6.0 18.0

Conclusion

In this tutorial, we learned the Python pandas DataFrame.div() method. We learned syntax, parameters, and solved examples by applying this method on the DataFrame and understood the method.



About the author:
I like writing about Python, and frameworks like Pandas, Numpy, Scikit, etc. I am still learning Python. I like sharing what I learn with others through my content.