Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

why do the following lines not work as I expect?

import numpy as np
a = np.array([0,1,2,1,1])
a[a==1][1:] = 3
print a
>>> [0 1 2 1 1]
# I would expect [0 1 2 3 3]

Is this a 'bug' or is there another recommended way to this?

On the other hand, the following works:

a[a==1] = 3
print a
>>> [0 3 2 3 3]

Cheers, Philipp

like image 745
Philipp der Rautenberg Avatar asked Nov 06 '09 13:11

Philipp der Rautenberg


1 Answers

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.

like image 69
robince Avatar answered Oct 16 '22 13:10

robince