NumPy:除以0,除以零

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"参数中保持不变.

  • 如果 `a` 和/或 `b` 可能是整数数组,那么它是相同的概念,您只需要显式设置正确的输出类型: `c = np.divide(a, b, out=np.zeros(a .shape, dtype=float), 其中=b!=0)` (4认同)
  • 如果有人对哪个最快感兴趣,这个方法比 @denis/@Franck Dernoncourt 的答案更快,运行一百万个周期,我得到 8 秒,而他们的得到 11 秒。 (2认同)
  • 就我而言,不仅需要“清零”的浮点值精确等于零,而且这些值“接近”零。因此,以下内容很有用 `np.divide(a, b, out=np.zeros_like(a), where=~np.isclose(b,np.zeros_like(b)))` 并且您可以设置 `atol` 和`isclose` 的 `rtol` 适合您的用例。 (2认同)

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

在其他答案的基础上,改进:

码:

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)

  • 检查 `0/0` 和 `1/0` 错误的好工作。 (2认同)

Ulf*_*lak 14

单线(投掷警告)

np.nan_to_num(array1 / array2)
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告诉你除以零的"错误",因为你已经打算这样做,并处理这种情况.

  • 您应该在上下文中执行除法`np.errstate(divide ='ignore'):` (5认同)