Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZeroDivisionError: float division by zero (python 3.6)

I am using the below code to bypass divide by zero error still getting one, not able to figure out what's actually going wrong here.

df.loc[:,'B to A Ratio'] =np.where(df.loc[:,'A']!=0,df.loc[:,'B']/df.loc[:,'A'],np.nan)

FYI, I am doing this operation on a data frame created from pivot table. Column 'A' & 'B' here are just for Illustration.

like image 862
Mohammad Akhtar Avatar asked Sep 14 '25 11:09

Mohammad Akhtar


1 Answers

As commented by @Divakar, when you use np.where, the division is still fully evaluated for all the values in the two series; To avoid dividing by zero, you can convert zeros to nan before division since any value divided by nan gives nan:

df = pd.DataFrame({
        "A": [1,2,0,3,4],
        "B": [0,2,1,0,1]
    })
​
df.B.div(df.A.where(df.A != 0, np.nan))

#0    0.00
#1    1.00
#2     NaN
#3    0.00
#4    0.25
#dtype: float64

Also not sure what your pandas version is, dividing by zero in pandas 0.19 ~ 0.20 gives inf instead of raising an error

df.B / df.A

#0    0.000000
#1    1.000000
#2         inf
#3    0.000000
#4    0.250000
#dtype: float64
like image 169
Psidom Avatar answered Sep 17 '25 05:09

Psidom