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?
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With