在函数中使用它时如何处理 pandas 中被零除的异常

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

我正在做除法的值为 0,这似乎会引发错误。如何避免这个错误

 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"

新栏只填了"Anomaly"如何更正上面的代码

预期输出

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

使用numpy.where:

import numpy as np

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

输出:

   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
df['remarks'] = np.where(((abs(df['pred wt']-df['wt']))/df['wt']).gt(0.25), "Weight Anomaly", 'Pass')

试试这个代码

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'))

我认为你输入的输出与功能不符。至少其中一个值应为 'Weight Anamoly'。调整 lt(0.25) 以获得您想要的结果。 lt 代表 'less than',您可以将其更改为 'gt'(大于)以满足您的需要