I have two numpy arrays a, b of the same shape, b has a few zeros. I would like to set an output array to a / b where b is not zero, and a otherwise. The following works, but yields a warning because a / b is computed everywhere first.
import numpy
a = numpy.random.rand(4, 5)
b = numpy.random.rand(4, 5)
b[b < 0.3] = 0.0
A = numpy.where(b > 0.0, a / b, a)
/tmp/l.py:7: RuntimeWarning: divide by zero encountered in true_divide
A = numpy.where(b > 0.0, a / b, a)
Filtering the division with a mask doesn't perserve the shape, so this doesn't work:
import numpy
a = numpy.random.rand(4, 5)
b = numpy.random.rand(4, 5)
b[b < 0.3] = 0.0
mask = b > 0.0
A = numpy.where(mask, a[mask] / b[mask], a)
ValueError: operands could not be broadcast together with shapes (4,5) (14,) (4,5)
Any hints on how to avoid the warning?
