Reputation: 69
I have an array 2*n of True and False boolean.
array([[False, True],
[False, True],
[False, True],
...,
[False, True],
[False, True],
[False, True]])
What I want is a new vector, can be in another array that has False if any of the two values are False. I can create a loop and check each value in the row, and make a new vector. but I'm guessing it's slow
boidx = np.empty(len(minindex), dtype=bool)
for idx in range(len(minindex)):
if minindex[idx,0] and minindex[idx,1]:
boidx[idx]=True
else:
boidx[idx]=False
but this is long and not pythonic. The array is either 2n or 4n. so it should cover those options (my for loop does not) but if needed, two solutions with an if for size is doable. I also tried to use numpy.isin() command. but it works for each cell. I need per row.
Upvotes: 1
Views: 4448
Reputation: 8903
If I understand correctly, a pythonic solution could use numpy.all
:
import numpy as np
minindex = np.array([[False, True],
[False, True],
[True, True],
[True, False],
[False, True],
[False, False],
[False, False],
[True, True]
boidx = np.array([np.all(i) for i in minindex])
and you get:
[False False True False False False False True]
Another solution could be the use of prod
:
boidx = np.array([bool(i.prod()) for i in minindex])
and you get the same result.
As suggested by @Jianyu, this way should be definitely faster:
boidx = np.all(minindex, axis=1)
Upvotes: 1
Reputation: 163
As an answer already pointed out, you can use numpy.all() to solve it.
A simpler formulation without any loop would be:
np.all(minindex, axis=1)
Upvotes: 6