Pandas div()

The div() method in Pandas is used to divide one DataFrame by another DataFrame, element-wise.

Example

import pandas as pd

# create a DataFrame
df1 = pd.DataFrame({
    'A': [10, 20, 30],
    'B': [40, 50, 60]
})

# create another DataFrame
df2 = pd.DataFrame({
    'A': [2, 10, 3],
    'B': [2, 50, 6]
})

# divide df1 by df2 using div() result = df1.div(df2)
print(result) ''' Output A B 0 5.0 20.0 1 2.0 1.0 2 10.0 10.0 '''

div() Syntax

The syntax of the div() method in Pandas is:

df.div(other, axis='columns')

div() Arguments

The div() method takes following arguments:

  • other - the denominator. This can be scalar, another DataFrame, or a Series.
  • axis (optional) - determines axis along which division is performed
  • fill_value (optional) - specifies a value to substitute for any missing values in the DataFrame or in the other object before division

div() Return Value

The div() method returns a new object of the same type as the caller, which is either a DataFrame or a Series, depending on what is being divided.


Example 1: Divide Two DataFrames

import pandas as pd

# define the first DataFrame
df1 = pd.DataFrame({
    'A': [5, 6],
    'B': [7, 8]
})

# define the second DataFrame
df2 = pd.DataFrame({
    'A': [1, 2],
    'B': [3, 4]
})

# divide df1 by df2 using div() result = df1.div(df2)
print(result)

Output

     A         B
0  5.0  2.333333
1  3.0  2.000000

In this example, df1.div(df2) divides each element of the df1 DataFrame by the corresponding element of the df2 DataFrame.


Example 2: DIvide DataFrame With a Scalar

import pandas as pd

# create a DataFrame
df = pd.DataFrame({
    'A': [2, 4, 6],
    'B': [8, 10, 12]
})

# scalar to div with
scalar_value = 2

# divide each element in df by scalar value result = df.div(scalar_value)
print(result)

Output

   A    B
0  1.0  4.0
1  2.0  5.0
2  3.0  6.0

Here, we divided each element in the df DataFrame by the scalar value of 2.


Example 3: Division of DataFrame by Series

import pandas as pd

# create a DataFrame 
df = pd.DataFrame({
    'A': [10, 200, 3000],  
    'B': [40, 500, 6000],  
    'C': [70, 800, 9000]  
})

# create two Series
series_for_columns = pd.Series([10, 100, 1000])
series_for_rows = pd.Series([10, 100, 1000], index=['A', 'B', 'C'])

# div along the columns (axis=0) result_columns = df.div(series_for_columns, axis=0)
print("Division along columns:") print(result_columns) print("\n")
# div along the rows (axis=1) result_rows = df.div(series_for_rows, axis=1)
print("Division along rows:") print(result_rows)

Output

Division along columns:
    A    B    C
0  1.0  4.0  7.0
1  2.0  5.0  8.0
2  3.0  6.0  9.0


Division along rows:
      A     B     C
0    1.0   0.4  0.07
1   20.0   5.0  0.80
2  300.0  60.0  9.00

Here,

  1. axis=0 - divides each column by the Series' values, matching by row index.
  2. axis=1 - divides each row by the Series' values, matching by column label.