Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logical_and with nested boolean arrays

I have one (very long) boolean array a with k True entries, and one boolean array b of length k. I would like to get a boolean array c that is True if and only if a "and" b are True:

import numpy

a = numpy.array([False, False, True, False, True, False])
b = numpy.array([True, False])

assert numpy.sum(a) == len(b)  # guaranteed

c = numpy.zeros(len(a), dtype=bool)
idx_b = 0
for k in range(len(a)):
    if a[k]:
        if b[idx_b]:
            c[k] = True
        idx_b += 1

print(c)
[False False  True False False False]

This here uses a loop, but I'm thinking there must a faster way with boolean indexing, but I can't quite get to it.

Any hints?

like image 662
Nico Schlömer Avatar asked Mar 01 '23 22:03

Nico Schlömer


2 Answers

Simply mask input array with itself (self-masking?) and assign -

a[a] = b

If you need output in a new array, copy the input array and perform masking on the same.

like image 118
Divakar Avatar answered Mar 06 '23 14:03

Divakar


If the assertion holds true, you can use np.flatnonzero

import numpy as np

a = np.array([False, False, True, False, True, False])
b = np.array([True, False])

assert np.sum(a) == len(b)

c = np.copy(a)
idx = np.flatnonzero(c) 
c[idx] = b

print(c)

Out:

[False, False,  True, False, False, False]
like image 31
Michael Szczesny Avatar answered Mar 06 '23 14:03

Michael Szczesny