Numpy: values ​​may not be assigned to a submatrix?

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

now a , as expected:

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

I want to assign a value to the sub-array a[ind_row, 1] and expect that I can do it this way:

 a[ind_row, 1][1] = 5 

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

+4
source share
1 answer

The problem is that advanced indexing creates a copy of the array, and only the copy changes. (This contrasts with basic indexing, which leads to the presentation of the source data.)

With the direct appointment of an advanced fragment

 a[ind_row, 1] = 3 

a copy is not created, but when used

 a[ind_row, 1][1] = 5 

part a[ind_row, 1] creates a copy and the indices of part [1] into this temporary copy. The copy is indeed modified, but since you are not referencing it, you do not see the changes and it immediately collects garbage.

This is similar to slicing standard Python lists (which also create 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] 

The solution to the problem for this simple case is obvious.

 a[ind_row[1], 1] = 5 

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

+9
source

Source: https://habr.com/ru/post/1379045/


All Articles