Tim Leathart Tim Leathart - 16 days ago 6
Python Question

Populate rows of empty matrix from another matrix by index array in numpy

I have an array:

arr = np.array([[ 5.1, 3.5, 1.4, 0.2],
[ 4.6, 3.1, 1.5, 0.2],
[ 5. , 3.6, 1.4, 0.2]])


and an index array:

index_arr = np.array([True, False, False, True, True])


and an empty matrix of zeros:

output = np.array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])


Is there a way that I can combine these using numpy functions/indexing tricks such that the rows of my array replace the rows in the zero matrix according to the index array? That is, I would end up with this as my final output

>>> array([[ 5.1, 3.5, 1.4, 0.2],
[ 0., 0., 0., 0. ],
[ 0., 0., 0., 0. ],
[ 4.6, 3.1, 1.5, 0.2],
[ 5. , 3.6, 1.4, 0.2]])


If it's not clear what I want to do here: the two middle rows of the output are empty because the second and third entry in
index_arr
are
False
. The first row of the
arr
is copied into the first row of the output, and the final two rows of the
arr
are copied into the final two rows of the output, as to line up with the
True
values in
index_arr
.

Answer

You can use logical vector indexing for subsetting and assignment:

output[index_arr] = arr

#array([[ 5.1,  3.5,  1.4,  0.2],
#       [ 0. ,  0. ,  0. ,  0. ],
#       [ 0. ,  0. ,  0. ,  0. ],
#       [ 4.6,  3.1,  1.5,  0.2],
#       [ 5. ,  3.6,  1.4,  0.2]])
Comments