Let’s say that I have an array like this:
JavaScript
x
6
1
array([[ 1, 2],
2
[-1, -2],
3
[ 0, 0],
4
[-1, 2],
5
[ 2, -1]])
6
I want to filter out all rows that include negative numbers in them.
And, hopefully, get this:
JavaScript
1
3
1
array([[ 1, 2],
2
[ 0, 0]])
3
I tried this so far:
JavaScript
1
5
1
>>> print(a[a>=0].reshape(3,2))
2
array([[1, 2],
3
[0, 0],
4
[2, 2]])
5
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.
JavaScript
1
13
13
1
import numpy as np
2
3
a = np.array([[ 1, 2],
4
[-1, -2],
5
[ 0, 0],
6
[-1, 2],
7
[ 2, -1]])
8
9
a[np.all(a >= 0, axis=1)]
10
# returns:
11
array([[1, 2],
12
[0, 0]])
13