[Numpy-discussion] numarray.where confusion

Perry Greenfield perry at stsci.edu
Wed May 26 12:03:06 CDT 2004

> > try 
> > 
> > x[m1[0][m2]] = array([10,20])
> > 
> > instead. The intent here is to provide x with the net index array
> > by indexing m1 first rather than indexing x first.
> > (note the odd use of m1[0]; this is necessary since where() will
> > return a tuple of index arrays (to allow use in multidimensional 
> > cases as indices, so the m1[0] extracts the array from the tuple;
> > Since m1 is a tuple, indexing it with another index array (well, 
> > tuple containing an index array) doesn't work).
> This works, but for the fact that in my real code I *am* dealing with
> multidimensional arrays.  But this is a nice trick to remember.
> (So, the following "does not work":
>     x = arange(9)
>     x.shape=(3,3)
>     m1 = where(x > 4)
>     m2 = where(x[m1] < 7)
>     x[m1[0][m2]]
> )
correct. You'd have to break apart the m1 tuple and
index all the components, e.g.,

m11, m12 = m1
x[m11[m2],m12[m2]] = ...

This gets clumsier with the more dimensions that must
be handled, but you still can do it. It would be most
useful if the indexed array is very large, the number
of items selected is relatively small and one
doesn't want to incur the memory overhead of all the
mask arrays of the admittedly much nicer notational
approach that Francesc illustrated.


More information about the Numpy-discussion mailing list