How to use numpy.where with logical operators

北慕城南 提交于 2019-11-30 11:44:36

问题


I'm trying to find the indices of all elements in an array that are greater than a but less than b. It's probably just a problem with my syntax but this doesn't work:

numpy.where((my_array > a) and (my_array < b))

How should I fix this? Or is there a better way to do it?

Thanks!


回答1:


Here are two ways:

In [1]: my_array = arange(10)

In [2]: where((my_array > 3) & (my_array < 7))
Out[2]: (array([4, 5, 6]),)

In [3]: where(logical_and(my_array > 3, my_array < 7))
Out[3]: (array([4, 5, 6]),)

For the first (replacing and with &), be careful to add parentheses appropriately: & has higher precedence than the comparison operators. You can also use *, but I wouldn't recommend it: it's hacky and doesn't make for readable code.

In [4]: where((my_array > 3) * (my_array < 7))
Out[4]: (array([4, 5, 6]),)


来源:https://stackoverflow.com/questions/13589390/how-to-use-numpy-where-with-logical-operators

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