Pandas DataFrame Division : div() function

Pandas dataframe.div() returns the floating divisions of dataframeand other element-wise. It is equivalent to dataframe / other, but with support to substitute a fill_value for missing data in one of the inputs.

Syntax

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

Parameters:

  • other: It is single or multiple element data structure or list-like object.
  • axis: It is used to represent the index which is '0' for index and '1' for the column, and in series input, axis to match Series index on.
  • level: By Default None. It is used specify int or label to broadcast across a level, matching Index values on the passed MultiIndex level.
  • fill_value:  By Default None.  It is used to fill missing values or any new elements for successful alignment of dataframe with this value before computation. If data in both the dataframe with the same location is missing then the result is also missing.

Returns:

It returns dataframe which is result of Arithmetic operation.

Examples

Using div() function to find the division of given dataframe with the help of series object.

import numpy as np
import pandas as pd

a = [11,21,35,46,57]
b = [10,30,50,40,60]
c = [33,45,67,76,55]

values = pd.DataFrame({'a':a,'b':b,'c':c})
values_0 = pd.Series([10,20,30,40,50])
values.div(values_0, axis=0)

Output:

  a b c
0 1.100000 1.000000 3.300000
1 1.050000 1.500000 2.250000
2 1.166667 1.666667 2.233333
3 1.150000 1.000000 1.900000
4 1.140000 1.200000 1.100000

When Null values are present

a = [12,22,34,46,58]
b = [10,30,50,40,60]
c = [np.NaN,np.NaN,np.NaN,np.NaN,np.NaN]

values=pd.DataFrame({'a':a,'b':b,'c':c})
values.div(2,fill_value=10)

Output:

  a b c
0 6.0 5.0 5.0
1 11.0 15.0 5.0
2 17.0 25.0 5.0
3 23.0 20.0 5.0
4 29.0 30.0 5.0

Tue, 02/16/2021 - 17:53

Authored by

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.