4
import numpy as np

a = np.zeros((3,2))
ind_row = np.array([0,1])    
a[ind_row, 1]=3

now, a is, as expected:

 [[ 0.  3.]
 [ 0.  3.]
 [ 0.  0.]]

I want to assign a value to a sub-array of a[ind_row, 1], and expect to be able to do this as follows:

a[ind_row, 1][1] = 5

However, this leaves a unchanged! Why should I expect this?

1 Answer 1

10

The problem here is that advanced indexing creates a copy of the array, and only the copy is modified. (This is in contrast to basic indexing, which results in a view into the original data.)

When directly assigning to an advanced slice

a[ind_row, 1] = 3

no copy is created, but when using

a[ind_row, 1][1] = 5

the a[ind_row, 1] part creates a copy, and the [1] part indexes into this temporary copy. The copy is indeed changed, but since you don't hold any references to it, you can't see the changes, and it is immediately garbage collected.

This is analogous to slicing standard Python lists (which also creates copies):

>>> a = range(5)
>>> a[2:4] = -1, -2
>>> a
[0, 1, -1, -2, 4]
>>> a[2:4][1] = -3
>>> a
[0, 1, -1, -2, 4]

A solution to the problem for this simple case is obviously

a[ind_row[1], 1] = 5

More complex cases could also be rewritten in a similar way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.