cm2115
cm2115

Reputation: 61

Why returning Zero Division Error instead of inf in dataframe?

getting a float division by zero error when I'm expecting inf where the divisor is 0

df['percent'] = df['value1'] / df['value2']

Here is the df:

enter image description here

ZeroDivisionError: float division by zero

It's absolutely acceptable for the df['percent'] to read infinity, but instead I have this error so the code doesn't run.

Upvotes: 1

Views: 5668

Answers (2)

constantstranger
constantstranger

Reputation: 9379

NOTE: pandas behaves differently for columns of different dtypes. It supports division by zero for columns with numeric dtype (such as float and int64) by returning a result of inf, but for columns of object type, it raises a ZeroDivisionError exception.

See my answer to a related question for examples.

Upvotes: 5

Derek O
Derek O

Reputation: 19600

If you are using the latest version of pandas, you should be able to divide by 0. I can run your code without getting a division by zero error.

If for some reason you are using a version of pandas that doesn't support division by 0, and cannot upgrade pandas for this particular problem, you can get around this error by using numpy.inf whenever df['value2'] = 0, and calculating the percentage normally otherwise:

import pandas as pd
import numpy as np

df = pd.DataFrame({'value1':[4,5,2,0.1],'value2':[8,7,0,0]})
df["percent"] = df.apply(lambda x: x['value1']/x['value2'] if x['value2'] != 0 else np.inf, axis=1)

Result:

>>> df
   value1  value2   percent
0     4.0       8  0.500000
1     5.0       7  0.714286
2     2.0       0       inf
3     0.1       0       inf

Upvotes: 2

Related Questions