简体   繁体   English

python波浪号一元运算符作为否定numpy bool数组

[英]python tilde unary operator as negation numpy bool array

Should be a simple question, but I'm unable to find an answer anywhere.应该是一个简单的问题,但我无法在任何地方找到答案。 The ~ operator in python is a documented as a bitwise inversion operator. python 中的~运算符被记录为按位反转运算符。 Fine.美好的。 I have noticed seemingly schizophrenic behavior though, to wit:不过,我注意到看似精神分裂的行为,即:

~True -> -2
~1 -> -2
~False -> -1
~0 -> -1
~numpy.array([True,False],dtype=int) -> array([-2,-1])
~numpy.array([True,False],dtype=bool) -> array([False,True])

In the first 4 examples, I can see that python is implementing (as documented) ~x = -(x+1) , with the input treated as an int even if it's boolean .在前 4 个示例中,我可以看到 python 正在实现(如文档所述) ~x = -(x+1)即使它是 boolean ,输入也被视为 int 。 Hence, for a scalar boolean, ~ is not treated as a logical negation.因此,对于标量布尔值, ~不被视为逻辑否定。 Not that the behavior is identical on a numpy array defined with boolean values by with an int type.并不是说在用 int 类型定义的布尔值的 numpy 数组上的行为是相同的。

Why does ~ then work as a logical negation operator on a boolean array (Also notice: ~numpy.isfinite(numpy.inf) -> True ?)?为什么~然后在布尔数组上用作逻辑否定运算符(另请注意: ~numpy.isfinite(numpy.inf) -> True ?)?

It is extremely annoying that I must use not() on a scalar, but not() won't work to negate an array.我必须在标量上使用not()非常烦人,但not()无法否定数组。 Then for an array, I must use ~ , but ~ won't work to negate a scalar...然后对于数组,我必须使用~ ,但是~无法否定标量...

not is implemented through the __nonzero__ special method, which is required to return either True or False , so it can't give the required result. not通过__nonzero__特殊方法实现,该方法需要返回TrueFalse ,因此无法给出所需的结果。 Instead the ~ operator is used, which is implemented through the __not__ special method.而是使用~操作符,它是通过__not__特殊方法实现的。 For the same reason, & and |出于同样的原因, &| are used in place of and and or .用于代替andor

PEP 335 aimed to allow overloading of boolean operators but was rejected because of excessive overhead (it would eg complicate if statements). PEP 335旨在允许布尔运算符的重载,但由于开销过多而被拒绝(例如,它会使if语句复杂化)。 PEP 225 suggests a general syntax for "elementwise" operators, which would provide a more general solution, but has been deferred. PEP 225建议了“逐元素”运算符的通用语法,这将提供更通用的解决方案,但已被推迟。 It appears that the current situation, while awkward, is not painful enough to force change.看来目前的情况虽然尴尬,但还不足以迫使改变。

np.isfinite when called on a scalar returns a value of type np.bool_ , not bool . np.isfinite在标量上np.isfinite时返回np.bool_类型的值,而不是bool np.bool_ is also the type you get when extracting a scalar value from an array of bool dtype. np.bool_也是从 bool dtype 数组中提取标量值时获得的类型。 If you use np.True_ and np.False_ in place of True and False you will get consistent behaviour under ~ .如果您使用np.True_np.False_代替TrueFalse您将在~下获得一致的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM