How to handle divide by zero exception in pandas while using it in a function

1.8k Views Asked by At

where the value are 0 on which i'am doing division, which seems to throw an error. How to avoid this error

 wt     pred wt  remarks
  0      14      Anomaly
  0      20      Anomaly
  25     30      Anomaly
  22     21      Anomaly
  21     102     Anomaly


     def valuation_formula(x,y):
         if float(abs(x-y)/y*100) > 25.0:
            return "Anomaly"
         else :
            return "Pass"

     try:
        df_Wt['Weight_Remarks'] = df_Wt.apply(lambda row: 
        valuation_formula(row['Predicted Weight'], row['Weight']), axis=1)

     except ZeroDivisionError:
        df_Wt['Weight_Remarks'] = "Anomaly"

The new column is only filled with "Anomaly" how do i correct this above code

Expected output

            wt      pred wt  remarks
            0        14      Anomaly
            0        20      Anomaly
           25        30      Pass
           22        21      Pass
           21        102     Anomaly
3

There are 3 best solutions below

0
moys On BEST ANSWER
df['remarks'] = np.where(((abs(df['pred wt']-df['wt']))/df['wt']).gt(0.25), "Weight Anomaly", 'Pass')
1
Chris On

Use numpy.where:

import numpy as np

df['new_remarks'] = np.where(df['wt'].ne(0), df['pred wt']/df['wt'], 'Anomaly')
print(df)

Output:

   wt  pred wt  remarks         new_remarks
0   0       14  Anomaly             Anomaly
1   0       20  Anomaly             Anomaly
2  25       30  Anomaly                 1.2
3  22       21  Anomaly  0.9545454545454546
1
moys On

Try this code

df['remarks']= np.where(df.wt.div(df.pred,fill_value=1).eq(0),'Anamoly',np.where(((abs(df['pred']-df['wt']))/df['wt']).lt(0.25), "Weight Anomaly", 'Pass'))

I think the output you have put does not match the function. At least one of the values should be 'Weight Anamoly'. Tweak lt(0.25) to get the result you want. lt stands for 'less than', you can change that to 'gt' (greater than) to suit your needs