It seems that the np.where function evaluates all the possible outcomes first, then it evaluates the condition later. This means that, in my case, it will evaluate square root of -5, -4, -3, -2, -1 even though it will not be used later on.
My code runs and works. But my problem is the warning. I avoided using a loop to evaluate each element, because it will run much slower than np.where.
So, here, I am asking
- Is there any way to make
np.whereevaluate the condition first? - Can I turn off just this specific warning? How?
- Another better way to do it if you have a better suggestion.
Here just a short example code corresponding my real code which is gigantic. But essentially has the same problem.
Input:
import numpy as np
c=np.arange(10)-5
d=np.where(c>=0, np.sqrt(c) ,c )
Output:
RuntimeWarning: invalid value encountered in sqrt
d=np.where(c>=0,np.sqrt(c),c)
d=np.where(c>=0, np.sqrt(c) ,c )is equivalent to[sqcv if cond else cv for (cond, sqcv, cv) in zip(c>=0, np.sqrt(c), c)]. In other words, the termnp.sqrt(c)is evaluated regardless of the conditionc>=0. - dobkind