1

I have two boolean arrays a and b. I want a resulting boolean array c such that each element in a is reversed if condition in b is True and keeps original if condition in b is false.

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

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

c = np.invert(a, where=b)

Expected output:

c = np.array([False, False, True, True, True])

However this is the output I'm getting:

c = np.array([False False False False  True])

Why is this so?

1
  • What about np.where(b, ~a, a)? Commented May 2, 2021 at 12:16

2 Answers 2

1

You need to include an out to specify the value for the not-where elements. Otherwise they are unpredictable.

In [242]: np.invert(a,where=b, out=a)
Out[242]: array([False, False,  True,  True,  True])
Sign up to request clarification or add additional context in comments.

Comments

0

Passing where=b to numpy.invert doesn't mean "keep the original a values for cells not selected by b". It means "don't write anything to the output array for cells not selected by b". Since you didn't pass an initialized out array, the unselected cells are filled with whatever garbage happened to be in that memory when it was allocated.

Since NumPy has some free lists for small array buffers, we can demonstrate that the output is uninitialized garbage by getting NumPy to reuse an allocation filled with whatever we want:

import numpy

a = numpy.zeros(4, dtype=bool)
numpy.array([True, False, True, False])
print(repr(numpy.invert(a, where=a)))

Output:

array([ True, False,  True, False])

In this example, we can see that NumPy reused the buffer from the array we created but didn't save. Since where=a selected no cells, numpy.invert didn't write anything to the buffer, and the result is exactly the contents of the discarded array.


As for the operation you wanted to perform, that's just XOR: c = a ^ b

2 Comments

Do I have to initialize an empty np.array and pass that to out?
@amnesic: The operation you're trying to do is XOR. You can just use ^.

Your Answer

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