如何在逻辑运算符中使用numpy.where [英] How to use numpy.where with logical operators
本文介绍了如何在逻辑运算符中使用numpy.where的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试查找数组中大于a但小于b的所有元素的索引.我的语法可能只是一个问题,但这不起作用:
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?
谢谢!
推荐答案
以下是两种方法:
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]),)
对于第一个(将and
替换为&
),请注意适当地添加括号:&
的优先级高于比较运算符.您也可以使用*
,但我不建议您使用它:hacky并且不能编写可读的代码.
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]),)
这篇关于如何在逻辑运算符中使用numpy.where的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文