2016-06-28 202 views
2

我有下面的代码:处理ZeroDivisonError的最佳方法?

def chunk_trades(A): 
    last = A[0] 
    new = [] 
    for x in A.iteritems(): 
     if np.abs((x[1]-last)/last) > 0.1: 
      new.append(x[1]) 
      last = x[1] 
     else: 
      new.append(last) 
    s = pd.Series(new, index=A.index) 
    return s 

有时last可以为零。在这种情况下,我希望它能够保持优雅,好像last几乎为零。

什么是最干净的方式?

+0

因此,如果'last'为零,您希望执行if代码块,而不是'else'代码块,对吗? –

+1

'if last == 0 or np.abs(...)> 0.1'?或者,按照您所描述的,定义一个“epsilon = 0.0000001”,然后执行“/(last或epsilon)”。当'last == 0'时它被认为是错误的,而'epsilon'将被用于它的位置。 – Bakuriu

+0

没错,我想让if块执行。 – cjm2671

回答

1

本只需更换您的线路:

if not last or np.abs((x[1]-last)/last) > 0.1: 

因为左断言首先检查这不会引发异常。

0

如果我正确anderstand,当last == 0 youl'll得到ZeroDivisionError,不是吗?如果是,请考虑以下稍微修改后的代码:

def chunk_trades(A): 
    last = A[0] 
    new = [] 
    for x in A.iteritems(): 
     try: 
      if np.abs((x[1]-last)/last) > 0.1: 
       new.append(x[1]) 
       last = x[1] 
      else: 
       new.append(last) 
     except ZeroDivisionError: 
      eps = 1e-18 # arbitary infinitesmall number 
      last = last + eps 
      if np.abs((x[1]-last)/last) > 0.1: 
       new.append(x[1]) 
       last = x[1] 
      else: 
       new.append(last) 

    s = pd.Series(new, index=A.index) 
    return s 
+0

你可以使用任何infinitesmall编号,而不是'1e-18' –