Pandas Tutorial Pandas References

Pandas DataFrame - truediv() function



The Pandas truediv() function returns floating division of dataframe and other, element-wise. It is equivalent to dataframe / other, but with support to substitute a fill_value for missing data as one of the parameters.

Syntax

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

Parameters

other Required. Specify any single or multiple element data structure, or list-like object.
axis Optional. Specify whether to compare by the index (0 or 'index') or columns (1 or 'columns'). For Series input, axis to match Series index on. Default is 'columns'.
level Optional. Specify int or label to broadcast across a level, matching Index values on the passed MultiIndex level. Default is None.
fill_value Optional. Specify value to fill existing missing (NaN) values, and any new element needed for successful DataFrame alignment. If data in both corresponding DataFrame locations is missing the result will be missing. Default is None.

Return Value

Returns the result of the arithmetic operation.

Example: using truediv() on whole DataFrame

In the example below, a DataFrame df is created. The truediv() function is used to divide the whole DataFrame by a given scalar value.

import pandas as pd
import numpy as np

df = pd.DataFrame({
  "Bonus": [5, 3, 2, 4],
  "Salary": [60, 62, 65, 59]},
  index= ["John", "Marry", "Sam", "Jo"]
)

print("The DataFrame is:")
print(df)

#dividing all entries of the DataFrame by 2
print("\ndf.truediv(2) returns:")
print(df.truediv(2))

The output of the above code will be:

The DataFrame is:
       Bonus  Salary
John       5      60
Marry      3      62
Sam        2      65
Jo         4      59

df.truediv(2) returns:
       Bonus  Salary
John     2.5    30.0
Marry    1.5    31.0
Sam      1.0    32.5
Jo       2.0    29.5

Example: Dividing different column by different value

Different column can be divided by different scalar value by providing other argument as a list. Consider the following example:

import pandas as pd
import numpy as np

df = pd.DataFrame({
  "Bonus": [5, 3, 2, 4],
  "Salary": [60, 62, 65, 59]},
  index= ["John", "Marry", "Sam", "Jo"]
)

print("The DataFrame is:")
print(df)

#dividing all entries of Bonus column by 2
#dividing all entries of Salary column by 10
print("\ndf.truediv([2,10]) returns:")
print(df.truediv([2,10]))

The output of the above code will be:

The DataFrame is:
       Bonus  Salary
John       5      60
Marry      3      62
Sam        2      65
Jo         4      59

df.truediv([2,10]) returns:
       Bonus  Salary
John     2.5     6.0
Marry    1.5     6.2
Sam      1.0     6.5
Jo       2.0     5.9

Example: using truediv() on selected columns

Instead of whole DataFrame, the truediv() function can be applied on selected columns. Consider the following example.

import pandas as pd
import numpy as np

df = pd.DataFrame({
  "Bonus": [5, 3, 2, 4],
  "Last Salary": [58, 60, 63, 57],
  "Salary": [60, 62, 65, 59]},
  index= ["John", "Marry", "Sam", "Jo"]
)

print("The DataFrame is:")
print(df)

#dividing all entries of Salary column by 3
print("\ndf['Salary'].truediv(3) returns:")
print(df["Salary"].truediv(3))

#dividing all entries of Salary column by 3
#dividing all entries of Bonus column by 2
print("\ndf[['Salary', 'Bonus']].truediv([3,2]) returns:")
print(df[["Salary", "Bonus"]].truediv([3,2]))

The output of the above code will be:

The DataFrame is:
       Bonus  Last Salary  Salary
John       5           58      60
Marry      3           60      62
Sam        2           63      65
Jo         4           57      59

df['Salary'].truediv(3) returns:
John     20.000000
Marry    20.666667
Sam      21.666667
Jo       19.666667
Name: Salary, dtype: float64

df[['Salary', 'Bonus']].truediv([3,2]) returns:
          Salary  Bonus
John   20.000000    2.5
Marry  20.666667    1.5
Sam    21.666667    1.0
Jo     19.666667    2.0

Example: Dividing columns in a DataDrame

The truediv() function can be applied in a DataFrame to get the floating division of two series/column element-wise. Consider the following example.

import pandas as pd
import numpy as np

df = pd.DataFrame({
  "Bonus": [5, 3, 2, 4],
  "Salary": [60, 62, 65, 59]},
  index= ["John", "Marry", "Sam", "Jo"]
)

print("The DataFrame is:")
print(df)

#dividing 'Bonus' by 'Salary' column
df['%Bonus'] = df['Bonus'].truediv(df['Salary'])
#converting into percentage
df['%Bonus'] = df['%Bonus']*100

print("\nThe DataFrame is:")
print(df)

The output of the above code will be:

The DataFrame is:
       Bonus  Salary
John       5      60
Marry      3      62
Sam        2      65
Jo         4      59

The DataFrame is:
       Bonus  Salary    %Bonus
John       5      60  8.333333
Marry      3      62  4.838710
Sam        2      65  3.076923
Jo         4      59  6.779661

❮ Pandas DataFrame - Functions