[SciPy-user] really basic where() function question

Alok Singhal as8ca@virginia....
Mon Aug 27 22:44:05 CDT 2007


On 27/08/07: 21:23, Michael Hearne wrote:
>    I'm trying to put together a presentation at work on Python, and I'm
>    confused about the where() numpy function.
>    The documentation, which is scant, indicates that where() requires three
>    input arguments:
>    where(condition,x,y) returns an array shaped like condition and has
>    elements of x and y where condition is respectively true or false
>    First, I have to admit that I don't understand what x and y are for here.
>    Second, I want to use where() like find() in Matlab - namely:
>    a = array([3,5,7,9])
>    i = where(a <= 6) => should return (array([0, 1]),)
>    (see http://www.scipy.org/Numpy_Example_List#head-7de97cb88f064612d2f339e9713a949cd7f2f804)
>    instead, I get this error:
>    ---------------------------------------------------------------------------
>    <type 'exceptions.TypeError'>             Traceback (most recent call
>    last)
>    /Users/mhearne/scipy/<ipython console> in <module>()
>    <type 'exceptions.TypeError'>: where() takes exactly 3 arguments (1 given)
>    What am I doing wrong?  Or did the usage of where() change since the
>    cookbook example was written?

What is the version of numpy you are running?  I get:

>>> import numpy
>>> numpy.__version__
'1.0.4.dev4015'
>>> a = numpy.array([3,5,7,9])
>>> i = numpy.where(a <= 6)
>>> i
(array([0, 1]),)
>>> a[i]
array([3, 5])

You could also try:

>>> i = numpy.where(a <= 6, 1, 0).astype('Bool')
>>> i
array([ True,  True, False, False], dtype=bool)
>>> a[i]
array([3, 5])

To answer your other question, if x and y are supplied, numpy.where()
returns an array of the same shape as the array in the first parameter.
The returned array has value x where the condition is True, and value
y where it is False:

>>> i = numpy.where(a <= 6, 1, 0)
>>> i
array([1, 1, 0, 0])

-Alok

-- 
Alok Singhal                               *   *          
Graduate Student, dept. of Astronomy   *           *     *
University of Virginia                                    
http://www.astro.virginia.edu/~as8ca/              *    * 


More information about the SciPy-user mailing list