Why does an assignment for double-sliced numpy arrays not work? Why does an assignment for double-sliced numpy arrays not work? numpy numpy

Why does an assignment for double-sliced numpy arrays not work?


It's related to how fancy indexing works. There is a thorough explanation here. It is done this way to allow inplace modification with fancy indexing (ie a[x>3] *= 2). A consequence of this is that you can't assign to a double index as you have found. Fancy indexing always returns a copy rather than a view.


It appears you simply can't do an assignment through a double-slice like that.

This works though:

a[numpy.where(a==1)[0][1:]] = 3


Because the a[a==1] part isn't actually a slice. It creates a new array. It makes sense when you think about it-- you're only taking the elements that satisfy the boolean condition (like a filter operation).