1

Let's say that I have an array like this:

array([[ 1,  2],
       [-1, -2],
       [ 0,  0],
       [-1,  2],
       [ 2, -1]])

I want to filter out all rows that include negative numbers in them.

And, hopefully, get this:

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

I tried this so far:

>>> print(a[a>=0].reshape(3,2))
array([[1, 2],
       [0, 0],
       [2, 2]])

But as you can see I get 1-dimensional array and I am getting unwanted rows (in this case is [2, 2])

How can I do this without using any for loop? Thanks in advance.

1 Answer 1

3

You can use np.all to check that all of the values in a row meet the condition.

import numpy as np 

a = np.array([[ 1,  2],
              [-1, -2],
              [ 0,  0],
              [-1,  2],
              [ 2, -1]])

a[np.all(a >= 0, axis=1)]
# returns:
array([[1, 2],
       [0, 0]])
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.