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.
Advertisement
Answer
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]])