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

Robert Kern robert.kern@gmail....
Mon Aug 27 22:50:40 CDT 2007

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:

It doesn't require 3; it can take either 1 or 3. It does that find()-like
behavior when given only one argument.

> 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.

They provide the actual values that will be in the result. There are a number of
use cases. For example, let's say you wanted to rectify an image: each pixel
with a value less than a threshold will become 0 and those at or above will be 255:

  img = where(img < theshold, 0, 255)

Or, let's say you wanted to leave the above-threshold values alone:

  img = where(img < threshold, 0, img)

> 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?

It works for me. Exactly what code did you type in? Copy-and-paste the whole
thing along with the traceback in context.

In [1]: from numpy import *

In [2]: a = array([3,5,7,9])

In [3]: i = where(a <= 6)

In [4]: i
Out[4]: (array([0, 1]),)

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

More information about the SciPy-user mailing list