[Numpy-discussion] problem with assigning to recarrays
Fri Feb 27 18:30:24 CST 2009
On Fri, Feb 27, 2009 at 18:26, Brian Gerke <email@example.com> wrote:
> I'm quite new to numpy and to python in general, so I apologize if I'm
> missing something obvious, but I've come across some seemingly nasty
> behavior when trying to assign values to the fields of an indexed
> subarray of a numpy record array. Perhaps an example would explain
> it best.
> First, I make a boring record array:
> In : r = rec.fromarrays([zeros(5), zeros(5)],
> This has five elements with two fields, all values are zero.
> Now I can change the values for field1 for a few of the array elements:
> In : r.field1=1
> In : r.field1=1
> Let's check and make sure that worked:
> In : print r.field1
> [ 0. 1. 0. 1. 0.]
> So far, so good.
> Now I want to change the value of field2 for those same elements:
> In : r[where(r.field1 == 1.)].field2 = 1
> Ok, so now the values of field 2 have been changed, for those elements
> In : r.field2
> Out: array([ 0., 0., 0., 0., 0.])
> Wait. What?
> That can't be right. Let's check again:
> In : print r[where(r.field1 == 1.)].field2
> [ 0. 0.]
> Ok, so it appears that I can *access* fields in this array with an
> array of indices, but I can't assign new values to fields so
> accessed. However, I *can* change the values if I use a scalar
> index. This is different from the behavior of ordinary arrays, for
> which I can reassign elements' values either way.
> Moreover, when I try to reassign record array fields by indexing with
> an array of indices, it would appear that nothing at all happens.
> This syntax is equivalent to the pass command.
> So, my question is this: is there some reason for this behavior in
> record arrays, which is unexpectedly different from the behavior of
> normal arrays, and rather confusing. If so, why does the attempt to
> assign values to fields of an indexed subarray not raise some kind of
> error, rather than doing nothing? I think it's unlikely that I've
> actually found a bug in numpy, but this behavior does not make sense
> to me.
r[where(r.field1 == 1.)] make a copy. There is no way for us to
construct a view onto the original memory for this circumstance given
numpy's memory model.
r[where(r.field1 == 1.)].field2 = 0.0 assigns to the copy.
"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 Numpy-discussion