using masks and numpy record arrays

Catherine Moroney Catherine.M.Moroney at jpl.nasa.gov
Wed May 25 16:27:19 EDT 2011


Hello,

I am trying to work with a structured array and a mask, and am 
encountering some problems.

For example:

 >>> xtype = numpy.dtype([("n", numpy.int32), ("x", numpy.float32)])
 >>> a = numpy.zeros((4), dtype=xtype)
 >>> b = numpy.arange(0,4)
 >>> a2 = numpy.zeros((4), dtype=xtype)
 >>> mask = numpy.where(b%2 == 0)
 >>> a2[:]["n"] += b            ! this changes the values of a2
 >>> a[mask]["n"] += b[mask]    ! this does not change the values of a
 >>> a2
array([(0, 0.0), (1, 0.0), (2, 0.0), (3, 0.0)],
       dtype=[('n', '<i4'), ('x', '<f4')])
 >>> a
array([(0, 0.0), (0, 0.0), (0, 0.0), (0, 0.0)],
       dtype=[('n', '<i4'), ('x', '<f4')])

Why do the values of a2 get updated, and yet the values of a do not?
How do I update a's contents using a mask?

If "a" is not a record array, but instead simply an array of ints, then
the a[mask] += b[mask] statement does alter the values of a.

 >>> a = numpy.zeros((4))
 >>> a[mask] += b[mask]
 >>> a
array([ 0.,  0.,  2.,  0.])

What is it about a numpy record array that prevents the mask statement
from working, and how do I get around this?

Thanks,

Catherine



More information about the Python-list mailing list