Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Post a Comment for "Zerodivisionerror: Float Division By Zero (python 3.6)"