Inverting a numpy boolean array using ~

PythonArraysNumpyBoolean OperationsNegation

Python Problem Overview


Can I use ~A to invert a numpy array of booleans, instead of the rather awkward functions np.logical_and() and np.invert()?

Indeed, ~ seems to work fine, but I can't find it in any nympy reference manual, and - more alarmingly - it certainly does not work with scalars (e.g. bool(~True) returns True !), so I'm a little bit worried ...

Python Solutions


Solution 1 - Python

short answer: YES

Ref:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.invert.html

Notice:

> Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ~.

and

> bitwise_not is an alias for invert:

>> np.bitwise_not is np.invert
>> True

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRolf BartstraView Question on Stackoverflow
Solution 1 - PythonsquidView Answer on Stackoverflow