Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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.

share|improve this question
up vote 3 down vote accepted

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]])
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.