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

2024-10-01 19:27:59 发布

您现在位置:Python中文网/ 问答频道 /正文

其中的值是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"

新列只填充了“异常”如何更正上面的代码

预期产量

^{pr2}$

Tags: dfreturnifdef错误rowweightwt
3条回答
df['remarks'] = np.where(((abs(df['pred wt']-df['wt']))/df['wt']).gt(0.25), "Weight Anomaly", 'Pass')

使用numpy.where

import numpy as np

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

输出:

^{pr2}$

试试这个代码

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)以获得所需的结果。它代表“小于”,您可以将其更改为“gt”(大于),以满足您的需要

相关问题 更多 >

    热门问题