Python 使用 ~ 反转 numpy 布尔数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13728708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:28:48  来源:igfitidea点击:

Inverting a numpy boolean array using ~

pythonarraysnumpybooleaninvert

提问by Rolf Bartstra

Can I use ~Ato 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 notwork with scalars (e.g. bool(~True)returns True!), so I'm a little bit worried ...

我可以~A用来反转布尔值的 numpy 数组,而不是相当笨拙的函数np.logical_and()np.invert()吗?事实上,~似乎工作正常,但我找不到它的任何nympy参考手册,以及-更令人担忧的-它的确不能与标量的工作(如bool(~True)退货True!),所以我有点担心...

回答by squid

short answer: YES

简短回答:是

Ref:

参考:

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

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 ~.

计算输入数组中整数的底层二进制表示的按位非。这个 ufunc 实现了 C/Python 操作符 ~。

and

bitwise_not is an alias for invert:

bitwise_not 是 invert 的别名:

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