问题
I am using numpy.where
, and I was wondering if there was a simply way to avoid calling the unused parameter. Example:
import numpy as np
z = np.array([-2, -1, 0, 1, -2])
np.where(z!=0, 1/z, 1)
returns:
array([-0.5, -1. , 1. , 1. , -0.5])
but I get a divide by zero warning because when z
was 0, the code still evaluates 1/z
even though it doesn't use it.
回答1:
You can also turn off the warning and turn it back on after you are done using the context manager errstate:
with np.errstate(divide='ignore'):
np.where(z!=0, 1/z, 1)
回答2:
You can apply a mask:
out = numpy.ones_like(z)
mask = z != 0
out[mask] = 1/z[mask]
回答3:
scipy has a little utility just for this purpose: https://github.com/scipy/scipy/blob/master/scipy/_lib/_util.py#L26
It's basically a matter of allocating the output array and using np.place
(or putmask) to fill exactly what you need.
来源:https://stackoverflow.com/questions/38276813/numpy-where-how-to-delay-evaluating-parameters