0

Say I have

>>> arr = np.array([True, True, False], dtype=bool)

Is it possible to call something like

>>> arr.flip_boolean_array_by_index(2)
[True, True, True]

2 Answers 2

2

You can use the bitwise-negation operator ~, or bitwise-xor (^) with 1.

arr[idx] = ~arr[idx]

or

arr[idx] ^= 1

idx can be an index, a slice, a "fancy" index, etc.

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

7 Comments

^= True might be cleaner.
I know how to do it in multiple steps. I want to know if there's a utility function that returns it in-place, it would read very nicely.
@user2357112 I indeed contemplated that. On one hand it is cleaner because we are doing a boolean operation. on the other hand, it is way more common to think about xor'ing bits than xor'ing (logical) boolean values...
@user3557216: There is such a function. I dunno if it reads very nicely, though, and it's a fairly new feature: numpy.logical_not.at(arr, 2).
or you could just make it nice and easy arr[idx] = not arr[idx] ... no need for binary negation ...
|
0

I found that ^= 1 on a dytpe=numpy.bool_ array gave a UFuncTypeError (can't cast from dtype int64 to dtype bool). However, ^= True works, e.g. arr[idx] ^= True. This was in numpy 1.26.3.

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.