1

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.

2 Answers 2

6

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)
Sign up to request clarification or add additional context in comments.

1 Comment

@sentence I'm actually not sure if np.logical_and(minindex[:, 0], minindex[:, 1]) would be even faster. It surely looks neater with np.all though
1

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)

1 Comment

Similarly, minindex.prod(1) should be used instead of your unpack-repack list comprehension (in cases where prod is more applicable than all).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.