Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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 ...
Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. This ufunc implements the C/Python operator ~.
bitwise_not is an alias for invert:
>> np.bitwise_not is np.invert
–
–
–
You can use the tilde if the array's dtype
is boolean and you are sure that this won't change as the software matures. However, np.logical_not
has two advantages:
It also works for object arrays, which can easily show up if np.nan
s or other objects make it into your array.
Its meaning is clear to anyone with a little background in logics.
There is also np.invert
but it doesn't work with object arrays and the word is ambiguous.
~np.array([False, True], dtype=bool)
Out[7]: array([ True, False])
~np.array([False, True], dtype=object)
Out[9]: array([-1, -2], dtype=object)
np.invert([True, False])
Out[4]: array([False, True])
np.invert((np.array([True, False], dtype=object)))
Out[5]: array([-2, -1], dtype=object)
np.logical_not(np.array([False, True], dtype=bool))
Out[8]: array([ True, False])
np.logical_not(np.array([False, True], dtype=object))
Out[10]: array([True, False], dtype=object)
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.