pythonpython-3.xpandasdataframedividebyzeroexception

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


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

Solution

  • df['remarks'] = np.where(((abs(df['pred wt']-df['wt']))/df['wt']).gt(0.25), "Weight Anomaly", 'Pass')