如何使用numpy.where与逻辑运算符

时间:2022-04-04 12:09:04

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:

我试图找到一个数组中大于a但小于b的所有元素的索引。这可能只是我的语法问题,但这不起作用:

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 个解决方案

#1


45  

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.

对于第一个(替换和使用&),请注意适当地添加括号:&具有比比较运算符更高的优先级。你也可以使用*,但我不推荐它:它很hacky并且没有代码可读。

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

#1


45  

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.

对于第一个(替换和使用&),请注意适当地添加括号:&具有比比较运算符更高的优先级。你也可以使用*,但我不推荐它:它很hacky并且没有代码可读。

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