numpy.where() and multiple comparisons
duncan smith
buzzard at invalid.invalid
Fri Jan 17 21:16:28 EST 2014
On 18/01/14 01:51, John Ladasky wrote:
> Hi folks,
>
> I am awaiting my approval to join the numpy-discussion mailing list, at scipy.org. I realize that would be the best place to ask my question. However, numpy is so widely used, I figure that someone here would be able to help.
>
> I like to use numpy.where() to select parts of arrays. I have encountered what I would consider to be a bug when you try to use where() in conjunction with the multiple comparison syntax of Python. Here's a minimal example:
>
> Python 3.3.2+ (default, Oct 9 2013, 14:50:09)
> [GCC 4.8.1] on linux
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import numpy as np
>>>> a = np.arange(10)
>>>> a
> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>> b = np.where(a < 5)
>>>> b
> (array([0, 1, 2, 3, 4]),)
>>>> c = np.where(2 < a < 7)
> 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()
>
> Defining b works as I want and expect. The array contains the indices (not the values) of a where a < 5.
>
> For my definition of c, I expect (array([3, 4, 5, 6]),). As you can see, I get a ValueError instead. I have seen the error message about "the truth value of an array with more than one element" before, and generally I understand how I (accidentally) provoke it. This time, I don't see it. In defining c, I expect to be stepping through a, one element at a time, just as I did when defining b.
>
> Does anyone understand why this happens? Is there a smart work-around? Thanks.
>
>>> a = np.arange(10)
>>> c = np.where((2 < a) & (a < 7))
>>> c
(array([3, 4, 5, 6]),)
>>>
Duncan
More information about the Python-list
mailing list