Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #6265

Re: using masks and numpy record arrays

From Robert Kern <robert.kern@gmail.com>
Subject Re: using masks and numpy record arrays
Date 2011-05-25 16:22 -0500
Organization The Church of Last Thursday
References <irjon7$883$1@news.jpl.nasa.gov>
Newsgroups comp.lang.python
Message-ID <mailman.2095.1306358584.9059.python-list@python.org> (permalink)

Show all headers | View raw


On 5/25/11 3:27 PM, Catherine Moroney wrote:
> Hello,
>
> I am trying to work with a structured array and a mask, and am encountering some
> problems.

You will want to ask numpy questions on the numpy mailing list:

   http://www.scipy.org/Mailing_Lists

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

Only the final [] on the left-hand side of the assignment actually turns into a 
.__setitem__() call to the object that is the result of the expression to its 
left. a[mask] makes a copy while a2[:] makes a view.

You could do

   a["n"][mask] += b[mask]

since a["n"] will also make a view and the .__setitem__() on it will propagate 
back to the original memory.

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

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

using masks and numpy record arrays Catherine Moroney <Catherine.M.Moroney@jpl.nasa.gov> - 2011-05-25 13:27 -0700
  Re: using masks and numpy record arrays Robert Kern <robert.kern@gmail.com> - 2011-05-25 16:22 -0500

csiph-web