6

I have a 2D numpy array of shape [6,2] and I want to remove the subarrays with the third element containing 0.

array([[0, 2, 1], #Input
       [0, 1, 1],
       [1, 1, 0],
       [1, 0, 2],
       [0, 2, 0],
       [2, 1, 2]])

array([[0, 2, 1], #Output
       [0, 1, 1],
       [1, 0, 2],
       [2, 1, 2]]) 

My code is positives = gt_boxes[np.where(gt_boxes[range(gt_boxes.shape[0]),2] != 0)]

It works but is there a simplified method to this?

1 Answer 1

14

You can use boolean indexing.

In [413]: x[x[:, -1] != 0]
Out[413]: 
array([[0, 2, 1],
       [0, 1, 1],
       [1, 0, 2],
       [2, 1, 2]])

  1. x[:, -1] will retrieve the last column

  2. x[:, -1] != 0 returns a boolean mask

  3. Use the mask to index into the original array

Sign up to request clarification or add additional context in comments.

2 Comments

Dang it. I didn't get to finish writing my solution, and it was still longer than this anyways. +1
@ChristianDean Yo that's how I feel 99% of the time in this tag :p

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.