i quite new python , numpy. can 1 pls me understand how can indexing of arrays used indices. have following 6 2d arrays this-
array([[2, 0], [3, 0], [3, 1], [5, 0], [5, 1], [5, 2]])
i want use these arrays indices , put value 10 in corresponding indices of new empty matrix. output should this-
array([[ 0, 0, 0], [ 0, 0, 0], [10, 0, 0], [10, 10, 0], [ 0, 0, 0], [10, 10, 10]])
so far have tried this-
numpy import* = array([[2,0],[3,0],[3,1],[5,0],[5,1],[5,2]]) b = zeros((6,3),dtype ='int32') b[a] = 10
but gives me wrong output. pls.
in [1]: import numpy np in [2]: = np.array([[2,0],[3,0],[3,1],[5,0],[5,1],[5,2]]) in [3]: b = np.zeros((6,3), dtype='int32') in [4]: b[a[:,0], a[:,1]] = 10 in [5]: b out[5]: array([[ 0, 0, 0], [ 0, 0, 0], [10, 0, 0], [10, 10, 0], [ 0, 0, 0], [10, 10, 10]])
why works:
if index b
two numpy arrays in assignment,
b[x, y] = z
then think of numpy moving simultaneously on each element of x
, each element of y
, each element of z
(let's call them xval
, yval
, zval
), , assigning b[xval, yval] value zval
. when z
constant, "moving on z
returns same value each time.
that's want, x
being first column of a
, y
being second column of a
. thus, choose x = a[:, 0]
, , y = a[:, 1]
.
b[a[:,0], a[:,1]] = 10
why b[a] = 10
not work
when write b[a]
, think of numpy creating new array moving on each element of a
, (let's call each 1 idx
) , placing in new array value of b[idx]
@ location of idx
in a
.
idx
value in a
. int32. b
of shape (6,3), b[idx]
row of b
of shape (3,). example, when idx
is
in [37]: a[1,1] out[37]: 0
b[a[1,1]]
in [38]: b[a[1,1]] out[38]: array([0, 0, 0])
so
in [33]: b[a].shape out[33]: (6, 2, 3)
so let's repeat: numpy creating new array moving on each element of a
, placing in new array value of b[idx]
@ location of idx
in a
. idx
moves on a
, array of shape (6,2) created. since b[idx]
of shape (3,), @ each location in (6,2)-shaped array, (3,)-shaped value being placed. result array of shape (6,2,3).
now, when make assignment like
b[a] = 10
a temporary array of shape (6,2,3) values b[a]
created, assignment performed. since 10 constant, assignment places value 10 @ each location in (6,2,3)-shaped array. values temporary array reassigned b
. see reference docs. values in (6,2,3)-shaped array copied (6,3)-shaped b
array. values overwrite each other. main point not obtain assignments desire.
Comments
Post a Comment