Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy: can values not be assigned to a sub-array?

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?

like image 994
Remi Avatar asked Dec 28 '22 11:12

Remi


1 Answers

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.

like image 164
Sven Marnach Avatar answered Jan 08 '23 16:01

Sven Marnach