hli*_*117 83 python arrays error-handling numpy divide-by-zero
我试图在python中执行元素明智的划分,但如果遇到零,我需要商才为零.
例如:
array1 = np.array([0, 1, 2])
array2 = np.array([0, 1, 1])
array1 / array2 # should be np.array([0, 1, 2])
Run Code Online (Sandbox Code Playgroud)
我总是可以通过我的数据使用for循环,但要真正利用numpy的优化,我需要除法函数在除以零错误时返回0而不是忽略错误.
除非我遗漏了某些内容,否则numpy.seterr()似乎不会在出错时返回值.有没有人有任何其他的建议,我可以如何通过零错误处理设置我自己的鸿沟来获得最好的numpy?
DSt*_*man 143
在numpy v1.7 +中,您可以利用ufunc的"where"选项.您可以在一行中执行操作,而无需处理errstate上下文管理器.
>>> a = np.array([-1, 0, 1, 2, 3], dtype=float)
>>> b = np.array([ 0, 0, 0, 2, 2], dtype=float)
# If you don't pass `out` the indices where (b == 0) will be uninitialized!
>>> c = np.divide(a, b, out=np.zeros_like(a), where=b!=0)
>>> print(c)
[ 0. 0. 0. 1. 1.5]
Run Code Online (Sandbox Code Playgroud)
在这种情况下,它在任何"b"不等于零的地方进行除法计算.当b确实等于零时,它在"out"参数中保持不变.
den*_*nis 41
建立在@Franck Dernoncourt的答案上,修正-1/0:
def div0( a, b ):
""" ignore / 0, div0( [-1, 0, 1], 0 ) -> [0, 0, 0] """
with np.errstate(divide='ignore', invalid='ignore'):
c = np.true_divide( a, b )
c[ ~ np.isfinite( c )] = 0 # -inf inf NaN
return c
div0( [-1, 0, 1], 0 )
array([0, 0, 0])
Run Code Online (Sandbox Code Playgroud)
Fra*_*urt 38
在其他答案的基础上,改进:
0/0通过添加invalid='ignore'来处理numpy.errstate()numpy.nan_to_num()转换np.nan为0.码:
import numpy as np
a = np.array([0,0,1,1,2], dtype='float')
b = np.array([0,1,0,1,3], dtype='float')
with np.errstate(divide='ignore', invalid='ignore'):
c = np.true_divide(a,b)
c[c == np.inf] = 0
c = np.nan_to_num(c)
print('c: {0}'.format(c))
Run Code Online (Sandbox Code Playgroud)
输出:
c: [ 0. 0. 0. 1. 0.66666667]
Run Code Online (Sandbox Code Playgroud)
Pi *_*ion 13
尝试分两步完成.先划分,然后更换.
with numpy.errstate(divide='ignore'):
result = numerator / denominator
result[denominator == 0] = 0
Run Code Online (Sandbox Code Playgroud)
该numpy.errstate行是可选的,只是阻止numpy告诉你除以零的"错误",因为你已经打算这样做,并处理这种情况.