我有下面的代码:处理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
几乎为零。
什么是最干净的方式?
因此,如果'last'为零,您希望执行if代码块,而不是'else'代码块,对吗? –
'if last == 0 or np.abs(...)> 0.1'?或者,按照您所描述的,定义一个“epsilon = 0.0000001”,然后执行“/(last或epsilon)”。当'last == 0'时它被认为是错误的,而'epsilon'将被用于它的位置。 – Bakuriu
没错,我想让if块执行。 – cjm2671