简体   繁体   English

numpy logical_and:意外行为

[英]numpy logical_and: unexpected behaviour

Let us say I give you the following boolean arrays: 我们假设我给你以下布尔数组:

b1 = np.array([ True,  True, False,  True ])
b2 = np.array([ True, False, False,  True ])
b3 = np.array([ True,  True,  True, False ])

If you AND them together, you would expect the following result: 如果你AND他们在一起,你会期望以下结果:

b4 = np.array([ True, False, False, False ])

Right? 对? If not, please explain. 如果没有,请解释。 If we agree, then, why does the following happen? 如果我们同意,那么,为什么会发生以下情况呢?

>>> np.logical_and(b1, b2, b3)
array([ True, False, False,  True ])

np.logical_and(np.logical_and(b1, b2), b3) does give the expected result. np.logical_and(np.logical_and(b1, b2), b3)确实给出了预期的结果。

Look at the documentation of np.logical_and . 查看np.logical_and文档 Like most of the NumPy operator functions, the third parameter is an out parameter, specifying a destination array. 与大多数NumPy运算符函数一样,第三个参数是out参数,指定目标数组。 It is not an operand! 不是一个操作数! Putting b3 there will simply overwrite the contents of b3 . b3放在那里只会覆盖b3的内容。

Using & is clearer and simpler in most cases: 在大多数情况下使用&更清晰,更简单:

b4 = b1 & b2 & b3

The third argument to np.logical_and is the optional out parameter, which stores the result of the operation. np.logical_and的第三个参数是可选的out参数,它存储操作的结果。

That is, calling np.logical_and(b1, b2, b3) overwrites b3 with the result of np.logical_and(b1, b2) . 也就是说,调用np.logical_and(b1, b2, b3)np.logical_and(b1, b2)的结果覆盖b3

Output arguments are useful for determining output type and general efficiency. 输出参数对于确定输出类型和一般效率很有用。

logical_and() is a binary operator, for your question, you can use: logical_and()是一个二元运算符,对于您的问题,您可以使用:

np.all([b1, b2, b3], axis=0)
np.logical_and.reduce([b1, b2, b3], axis=0)

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

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