1

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.

1 Answer 1

3

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]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.