如何以0除以返回0

时间:2014-10-08 03:13:06

标签: python arrays numpy error-handling 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])

我总是可以通过我的数据使用for循环,但要真正利用numpy的优化,我需要除法函数在除以零错误时返回0而不是忽略错误。

除非我遗漏某些内容,否则numpy.seterr()似乎无法在出错时返回值。有没有人有任何其他的建议,我可以在设置我自己的零差错处理时如何从numpy中获得最佳效果?

8 个答案:

答案 0 :(得分:108)

在numpy v1.7 +中,您可以利用ufuncs的“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]

在这种情况下,它会在任何“b”不等于零的地方进行除法计算。当b确实等于零时,它将保持与你在'out'参数中最初给出的值无关。

答案 1 :(得分:37)

在@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])

答案 2 :(得分:36)

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

代码:

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))

输出:

c: [ 0.          0.          0.          1.          0.66666667]

答案 3 :(得分:13)

单线(抛出警告)

np.nan_to_num(array1 / array2)

答案 4 :(得分:12)

尝试分两步完成。先划分,然后更换。

with numpy.errstate(divide='ignore'):
    result = numerator / denominator
    result[denominator == 0] = 0

numpy.errstate行是可选的,只是阻止numpy告诉你除以零的“错误”,因为你已经打算这样做,并处理这种情况。

答案 5 :(得分:2)

您也可以根据inf进行替换,仅当数组dtypes为浮点数时才按this answer进行替换:

>>> a = np.array([1,2,3], dtype='float')
>>> b = np.array([0,1,3], dtype='float')
>>> c = a / b
>>> c
array([ inf,   2.,   1.])
>>> c[c == np.inf] = 0
>>> c
array([ 0.,  2.,  1.])

答案 6 :(得分:0)

我发现搜索相关问题的一个答案是根据分母是否为零来操纵输出。

假设arrayAarrayB已初始化,但arrayB有一些零。如果我们想安全地计算arrayC = arrayA / arrayB,我们可以执行以下操作。

在这种情况下,每当我在其中一个单元格中除以零时,我将单元格设置为等于myOwnValue,在这种情况下为零

myOwnValue = 0
arrayC = np.zeros(arrayA.shape())
indNonZeros = np.where(arrayB != 0)
indZeros = np.where(arrayB = 0)

# division in two steps: first with nonzero cells, and then zero cells
arrayC[indNonZeros] = arrayA[indNonZeros] / arrayB[indNonZeros]
arrayC[indZeros] = myOwnValue # Look at footnote

脚注:回想起来,无论如何这条线是不必要的,因为arrayC[i]被实例化为零。但如果是myOwnValue != 0的情况,则此操作会执行某些操作。

答案 7 :(得分:0)

另一个值得一提的解决方案:

>>> a = np.array([1,2,3], dtype='float')
>>> b = np.array([0,1,3], dtype='float')
>>> b_inv = np.array([1/i if i!=0 else 0 for i in b])
>>> a*b_inv
array([0., 2., 1.])