Python 如何用除以零返回 0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26248654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return 0 with divide by zero
提问by hlin117
I'm trying to perform an element wise divide in python, but if a zero is encountered, I need the quotient to just be zero.
我正在尝试在 python 中执行元素智能除法,但如果遇到零,我需要商为零。
For example:
例如:
array1 = np.array([0, 1, 2])
array2 = np.array([0, 1, 1])
array1 / array2 # should be np.array([0, 1, 2])
I could always just use a for-loop through my data, but to really utilize numpy's optimizations, I need the divide function to return 0 upon divide by zero errors instead of ignoring the error.
我总是可以在我的数据中使用 for 循环,但要真正利用 numpy 的优化,我需要除以零错误时除法函数返回 0 而不是忽略错误。
Unless I'm missing something, it doesn't seem numpy.seterr()can return values upon errors. Does anyone have any other suggestions on how I could get the best out of numpy while setting my own divide by zero error handling?
除非我遗漏了什么,否则numpy.seterr()似乎不能在出错时返回值。有没有人对如何在设置自己的除以零错误处理时充分利用 numpy 有任何其他建议?
采纳答案by DStauffman
In numpy v1.7+, you can take advantage of the "where" option for ufuncs. You can do things in one line and you don't have to deal with the errstate context manager.
在 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]
In this case, it does the divide calculation anywhere 'where' b does not equal zero. When b does equal zero, then it remains unchanged from whatever value you originally gave it in the 'out' argument.
在这种情况下,它会在 b 不等于零的任何地方进行除法计算。当 b 等于 0 时,它与您最初在 'out' 参数中给出的任何值保持不变。
回答by Pi Marillion
Try doing it in two steps. Division first, then replace.
尝试分两步完成。先分区,再替换。
with numpy.errstate(divide='ignore'):
result = numerator / denominator
result[denominator == 0] = 0
The numpy.errstateline is optional, and just prevents numpy from telling you about the "error" of dividing by zero, since you're already intending to do so, and handling that case.
该numpy.errstate行是可选的,只是防止 numpy 告诉您除以零的“错误”,因为您已经打算这样做并处理这种情况。
回答by atomh33ls
You can also replace based on inf, only if the array dtypes are floats, as per this answer:
您也可以替换基于inf,仅当数组 dtypes 是浮点数时,根据此答案:
>>> 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.])
回答by hlin117
One answer I found searching a related question was to manipulate the output based upon whether the denominator was zero or not.
我在搜索相关问题时发现的一个答案是根据分母是否为零来操纵输出。
Suppose arrayAand arrayBhave been initialized, but arrayBhas some zeros. We could do the following if we want to compute arrayC = arrayA / arrayBsafely.
假设arrayA和arrayB已经初始化,但arrayB有一些零。如果我们想arrayC = arrayA / arrayB安全计算,我们可以执行以下操作。
In this case, whenever I have a divide by zero in one of the cells, I set the cell to be equal to myOwnValue, which in this case would be zero
在这种情况下,每当我在其中一个单元格中除以零时,我都会将该单元格设置为等于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
Footnote: In retrospect, this line is unnecessary anyways, since arrayC[i]is instantiated to zero. But if were the case that myOwnValue != 0, this operation would do something.
脚注:回想起来,这条线无论如何都是不必要的,因为它arrayC[i]被实例化为零。但如果是这样的话myOwnValue != 0,这个操作就会有所作为。
回答by Franck Dernoncourt
Building on the other answers, and improving on:
建立在其他答案的基础上,并改进:
0/0handling by addinginvalid='ignore'tonumpy.errstate()- introducing
numpy.nan_to_num()to convertnp.nanto0.
0/0通过增加处理invalid='ignore'到numpy.errstate()- 介绍
numpy.nan_to_num()转换np.nan为0.
Code:
代码:
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))
Output:
输出:
c: [ 0. 0. 0. 1. 0.66666667]
回答by denis
Building on @Franck Dernoncourt's answer, fixing -1 / 0:
以@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])
回答by Ulf Aslak
One-liner(throws warning)
单线(抛出警告)
np.nan_to_num(array1 / array2)
回答by T. Gwen
An other solution worth mentioning :
另一个值得一提的解决方案:
>>> 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.])

