Reputation: 560
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
.
Upvotes: 1
Views: 67
Reputation: 214927
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]])
Upvotes: 3