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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With