[Numpy-discussion] numarray.where confusion

Todd Miller jmiller at stsci.edu
Wed May 26 08:42:16 CDT 2004


On Wed, 2004-05-26 at 10:48, Alok Singhal wrote:
> Hi,
> 
> I am having trouble understanding how exactly "where" works in
> numarray.
> 
> What I am trying to do:
> 
> I am preparing a two-level mask in an array and then assign values to
> the array where both masks are true:
> 
> >>> from numarray import *
> >>> a = arange(10)
> >>> # First mask
> >>> m1 = where(a > 5)
> >>> a[m1]
> array([6, 7, 8, 9])
> >>> # Second mask
> >>> m2 = where(a[m1] < 8)
> >>> a[m1][m2]

a[m1] is a new array here.

> array([6, 7])
> >>> # So far so good
> >>> # Now change some values
> >>> a[m1][m2] = array([10, 20])

And here too.  This does a write into what is effectively a temporary
variable returned by the expression a[m1].  Although the write occurs,
it is lost.

> >>> a[m1][m2]
> array([6, 7])
> >>> a
> array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Here's how I did it (there was an easier way I overlooked):

a = arange(10)
m1 = where(a > 5, 1, 0).astype('Bool')
m2 = where(a < 8, 1, 0).astype('Bool')
a[m1 & m2] = array([10, 20])

The principle here is to keep the masks as "full sized" boolean arrays
rather than index arrays so they can be combined using the bitwise and
operator.   The resulting mask can be used to index just once
eliminating the temporary.

Regards,
Todd





More information about the Numpy-discussion mailing list