[SciPy-User] numpy.where() issue

Nathaniel Smith njs at pobox.com
Wed Jul 15 14:32:15 EDT 2015


On Jul 15, 2015 13:16, "Gabriele Brambilla" <gb.gabrielebrambilla at gmail.com>
wrote:
>
> I have problems with numpy.where
>
> why if I write
> deathnote0 = np.where(Yy > 0.02 or Yy < -0.02)

The problem is the 'or'. It's an unfortunate limitation of
python-the-language that 'or' only works on scalar values, and there's no
way for numpy to fix this. (The reason python works this way is that 'or'
is actually a flow-control construct, like 'if' -- it basically does 'if Yy
> 0.02: return True; elif Yy < -0.02: return True; else: return False'.
Notice that to decide whether to take the second branch and evaluate the
second comparison, it has to reduce the first comparison to a single
true/false value: it can't both take the branch and not take the branch at
different points in the array. So it makes sense that python works this
way, it's just annoying :-(.)

Instead, use the bitwise or operator, which is allowed to be overridden,
and for Boolean arrays will give you an elementwise or:
  (Yy > 0.02) | (Yy < -0.02)
Unfortunately the parentheses are necessary, because | has higher
precedence than < and >.

As a matter of style, I also strongly suggest using np.nonzero instead of
np.where: np.where is just a confusing wrapper function that calls
np.nonzero on single argument inputs, and in other cases does other things.

-n
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.scipy.org/pipermail/scipy-user/attachments/20150715/e4d9ff1e/attachment.html>


More information about the SciPy-User mailing list