[Numpy-discussion] Conditional update of recarray field
Wed Nov 28 08:26:48 CST 2012
Thanks for answer, Francesc.
I understand now that fancy indexing returns a copy of a recarray. Is
it also true for standard ndarrays? If so, I do not understand why
X['a'][cond]=-1 should work.
On Wed 28 Nov 2012 03:05:37 PM CET, Francesc Alted wrote:
> On 11/28/12 1:47 PM, Bartosz wrote:
>> I try to update values in a single field of numpy record array based on
>> a condition defined in another array. I found that that the result
>> depends on the order in which I apply the boolean indices/field names.
>> For example:
>> cond = np.zeros(5, dtype=np.bool)
>> cond[2:] = True
>> X = np.rec.fromarrays([np.arange(5)], names='a')
>> X[cond]['a'] = -1
>> print X
>> returns: [(0,) (1,) (2,) (3,) (4,)] (the values were not updated)
>> X['a'][cond] = -1
>> print X
>> returns: [(0,) (1,) (-1,) (-1,) (-1,)] (it worked this time).
>> I find this behaviour very confusing. Is it expected?
> Yes, it is. In the first idiom, X[cond] is a fancy indexing operation
> and the result is not a view, so what you are doing is basically
> modifying the temporary object that results from the indexing. In the
> second idiom, X['a'] is returning a *view* of the original object, so
> this is why it works.
>> Would it be
>> possible to emit a warning message in the case of "faulty" assignments?
> The only solution that I can see for this is that the fancy indexing
> would return a view, and not a different object, but NumPy containers
> are not prepared for this.
More information about the NumPy-Discussion