Difference between numpy.logical_and and &

给你一囗甜甜゛ 提交于 2019-12-03 22:54:20

@user1121588 answered most of this in a comment, but to answer fully...

"Bitwise and" (&) behaves much the same as logical_and on boolean arrays, but it doesn't convey the intent as well as using logical_and, and raises the possibility of getting misleading answers in non-trivial cases (packed or sparse arrays, maybe).

To use logical_and on multiple arrays, do:

np.logical_and.reduce([a, b, c])

where the argument is a list of as many arrays as you wish to logical_and together. They should all be the same shape.

I have been googling some official confirmation that I can use & instead of logical_and on NumPy bool arrays, and found one in the NumPy v1.15 Manual: "If you know you have boolean arguments, you can get away with using NumPy’s bitwise operators, but be careful with parentheses, like this: z = (x > 1) & (x < 2). The absence of NumPy operator forms of logical_and and logical_or is an unfortunate consequence of Python’s design.". So one can also use ~ for logical_not and | for logical_or.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!