5

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?

2
  • So out of bounds is treated as False? Commented Nov 10, 2020 at 19:01
  • out-of-bounds how? Commented Nov 10, 2020 at 19:01

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.