Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #64211

numpy.where() and multiple comparisons

Newsgroups comp.lang.python
Date 2014-01-17 17:51 -0800
Message-ID <5617a90f-3d9b-48b2-b449-9e5ef4c181e5@googlegroups.com> (permalink)
Subject numpy.where() and multiple comparisons
From John Ladasky <john_ladasky@sbcglobal.net>

Show all headers | View raw


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.

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

numpy.where() and multiple comparisons John Ladasky <john_ladasky@sbcglobal.net> - 2014-01-17 17:51 -0800
  Re: numpy.where() and multiple comparisons duncan smith <buzzard@invalid.invalid> - 2014-01-18 02:16 +0000
    Re: numpy.where() and multiple comparisons John Ladasky <john_ladasky@sbcglobal.net> - 2014-01-17 20:00 -0800
      Re: numpy.where() and multiple comparisons Peter Otten <__peter__@web.de> - 2014-01-18 09:50 +0100
        Re: numpy.where() and multiple comparisons Tim Roberts <timr@probo.com> - 2014-01-18 13:20 -0800
      'and' is not exactly an 'operator' (was Re: numpy.where() and multiple comparisons) Terry Reedy <tjreedy@udel.edu> - 2014-01-18 19:12 -0500

csiph-web