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.
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.
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?
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.
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.
One-liner (throws warning)
Try doing it in two steps. Division first, then replace.
The
numpy.errstate
line 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.One answer I found searching a related question was to manipulate the output based upon whether the denominator was zero or not.
Suppose
arrayA
andarrayB
have been initialized, butarrayB
has some zeros. We could do the following if we want to computearrayC = arrayA / arrayB
safely.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 zeroFootnote: In retrospect, this line is unnecessary anyways, since
arrayC[i]
is instantiated to zero. But if were the case thatmyOwnValue != 0
, this operation would do something.An other solution worth mentioning :
You can also replace based on
inf
, only if the array dtypes are floats, as per this answer: