python 3.x - numpy assignment doesn't work -


suppose have following numpy.array:

in[]: x out[]:  array([[1, 2, 3, 4, 5],        [5, 2, 4, 1, 5],        [6, 7, 2, 5, 1]], dtype=int16)   in[]: y out[]:  array([[-3, -4],        [-4, -1]], dtype=int16) 

i want replace sub array of x y , tried following:

in[]: x[[0,2]][:,[1,3]]= y 

ideally, wanted happen:

in[]: x out[]:  array([[1, -3, 3, -4, 5],        [5, 2, 4, 1, 5],        [6, -4, 2, -1, 1]], dtype=int16) 

the assignment line doesn't give me error, when check output of x

 in[]: x 

i find x hasn't changed, i.e. assignment didn't happen.

how can make assignment? why did assignment didn't happen?

the "fancy indexing" x[[0,2]][:,[1,3]] returns copy of data. indexing slices returns view. assignment happen, copy (actually copy of copy of...) of x.

here see indexing returns copy:

>>> x[[0,2]] array([[1, 2, 3, 4, 5],        [6, 7, 2, 5, 1]], dtype=int16) >>> x[[0,2]].base x false >>> x[[0,2]][:, [1, 3]].base x false >>> 

now can use fancy indexing set array values, not when nest indexing.

you can use np.ix_ generate indices , perform assignment:

>>> x[np.ix_([0, 2], [1, 3])] array([[2, 4],        [7, 5]], dtype=int16) >>> np.ix_([0, 2], [1, 3]) (array([[0],        [2]]), array([[1, 3]])) >>> x[np.ix_([0, 2], [1, 3])] = y >>> x array([[ 1, -3,  3, -4,  5],        [ 5,  2,  4,  1,  5],        [ 6, -4,  2, -1,  1]], dtype=int16) >>> 

you can make work broadcasted fancy indexing (if that's term) it's not pretty

>>> x[[0, 2], np.array([1, 3])[..., none]] = y >>> x array([[ 1, -3,  3, -4,  5],        [ 5,  2,  4,  1,  5],        [ 6, -4,  2, -1,  1]], dtype=int16) 

by way, there interesting discussion @ moment on numpy discussion mailing list on better support "orthogonal" indexing may become easier in future.


Popular posts from this blog