简体   繁体   中英

Assign to Logical Indexed Numpy Array

So, I know that you can do this by doing

>>> arr[mask] = value

However, if I want to make the code shorter (and not recompute the mask and index each time), I'd like to do something like this:

>>> sub = arr[mask]
>>> sub[...] = value # This works in other cases, but not this one.

My understanding is that doing Ellipses indexing should allow you to specify that you're not reassigning a given variable, but are rather broadcasting to the actual array.

So, here's the question: why doesn't it work?

My thinking is that it's related to the fact that:

>>> arr[mask] is arr[mask]
False

But surely since the mask indexed versions are just views (not copies of the underlying structure), this shouldn't break assignment.

arr[mask] is a copy. arr[mask]=... looks the same, but actually is a different assignment operation. Elsewhere I've explained this in terms of calls to __getitem__ and __setitem__ .

But surely since the mask indexed versions are just views (not copies of the underlying structure), this shouldn't break assignment.

The reason why this doesn't work is that indexing with masks will create a copy, not a view :

Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM