[Numpy-discussion] Conditional update of recarray field
Francesc Alted
francesc@continuum...
Wed Nov 28 08:05:37 CST 2012
On 11/28/12 1:47 PM, Bartosz wrote:
> Hi,
>
> 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.
--
Francesc Alted
More information about the NumPy-Discussion
mailing list