0

Suppose we have:

>>> x
array([-1. , -1.3,  0. ,  1.3,  0.2])

We can choose select elements with a range:

>>> x[x <= 1]
array([-1. , -1.3,  0. ,  0.2])

And we can bound it below too:

>>> x[-1 <= x]
array([-1. ,  0. ,  1.3,  0.2])

Is there some rationale for not being able to use the following:

>>> x[-1 <= x <= 1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I know that all it does is create a mask of True and Falses upon doing these inequality operations, and so I can do the following:

>>> x[(-1 <= x) * (x <= 1)]
array([-1. ,  0. ,  0.2])

as a broadcasting operation on booleans. It's not too inconvenient, but why doesn't the previous range inequality work?

OneRaynyDay
  • 3,658
  • 2
  • 23
  • 56

1 Answers1

1

Although regular Python types do support "chained comparison" like 1 < x < 5, NumPy arrays do not. Perhaps that's unfortunate, but you can work around it easily:

x[(-1 <= x) & (x <= 1)]
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Better to use `np.logical_and`. – Mazdak Jul 22 '18 at 08:44
  • @Kasramvd: What's better about it? – John Zwinck Jul 22 '18 at 08:44
  • `&` is generally a bit-wise `and` and the reason it works as expected here has nothing to do with the intention behind using it. So for refusing of such confusions it's better to use a `logical_and` function. – Mazdak Jul 22 '18 at 08:47
  • @Kasramvd: I think you'll agree they give the same result. It also happens that `&` is a bit faster (15% faster on my system). Plus, `&` is quite conventional, and can be seen in lots of NumPy code "in the wild" (whereas if we were writing C I would agree with you not to use `&`). – John Zwinck Jul 22 '18 at 09:06
  • 1
    @kasravnd This usage is explicitly mentioned by the doc: "The ``&`` operator can be used as a shorthand for ``np.logical_and`` on boolean ndarrays.". – Aubergine Jun 04 '21 at 04:17