Pandas division by zero

Division by zero in Pandas

When performing division operations on data using Pandas, there is a possibility of encountering division by zero errors. This can happen when dividing a number by zero or when dividing a series/column by another series/column which contains zero values.

Example 1: Division by zero error


import pandas as pd

data = {'A': [1, 2, 3, 4, 5],
        'B': [0, 0, 0, 0, 0]}

df = pd.DataFrame(data)

# Performing division operation on column A by column B
df['C'] = df['A'] / df['B']
    

In this example, we have a DataFrame with two columns ‘A’ and ‘B’. ‘B’ column contains all zeros. When we try to divide ‘A’ column by ‘B’ column, a division by zero error will occur because dividing any non-zero number by zero is mathematically undefined.

Example 2: Handling division by zero errors


import pandas as pd
import numpy as np

data = {'A': [1, 2, 3, 4, 5],
        'B': [0, 0, 0, 0, 0]}

df = pd.DataFrame(data)

# Handling division by zero using np.where()
df['C'] = np.where(df['B'] != 0, df['A'] / df['B'], 0)
    

In this example, we handle the division by zero error by using the NumPy np.where() function. We check if the values in column ‘B’ are not equal to zero, and if so, perform the division of ‘A’ by ‘B’. If the values in ‘B’ are zero, we assign a default value of 0 to the resulting column ‘C’. This way, we avoid the division by zero error and ensure that the division operation is only performed when it is mathematically valid.

Leave a comment