Numpy chain comparison with two predicates

喜夏-厌秋 提交于 2020-01-11 08:08:27

问题


In Numpy, I can generate a boolean array like this:

>>> arr = np.array([1, 2, 1, 2, 3, 6, 9])
>>> arr > 2
array([False, False, False, False,  True,  True,  True], dtype=bool)

Is is possible to chain comparisons together? For example:

>>> 6 > arr > 2
array([False, False, False, False,  True,  False,  False], dtype=bool)

回答1:


AFAIK the closest you can get is to use &, |, and ^:

>>> arr = np.array([1, 2, 1, 2, 3, 6, 9])
>>> (2 < arr) & (arr < 6)
array([False, False, False, False,  True, False, False], dtype=bool)
>>> (2 < arr) | (arr < 6)
array([ True,  True,  True,  True,  True,  True,  True], dtype=bool)
>>> (2 < arr) ^ (arr < 6)
array([ True,  True,  True,  True, False,  True,  True], dtype=bool)

I don't think you'll be able to get a < b < c-style chaining to work.




回答2:


You can use the numpy logical operators to do something similar.

>>> arr = np.array([1, 2, 1, 2, 3, 6, 9])
>>> arr > 2
array([False, False, False, False,  True,  True,  True], dtype=bool)
>>>np.logical_and(arr>2,arr<6)
Out[5]: array([False, False, False, False,  True, False, False], dtype=bool)


来源:https://stackoverflow.com/questions/17075324/numpy-chain-comparison-with-two-predicates

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