2016-06-28 157 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' –