这个numpy.where()方法可以适应两个条件而不是一个吗?

时间:2017-07-07 05:12:58

标签: python-3.x numpy indexing multiple-conditions

我可以让numpy.where()为一个条件而不是两个条件工作。

对于一个条件:

import numpy as np

a = np.array([1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 1, 1, 1, 2, 4, 5])
i, = np.where(a < 2)
print(i)
>> [ 0  5  8 10 11 12] ## indices where a[i] = 1

有两个条件:

# condition = (a > 1 and a < 3)
# i, = np.where(condition)
i, = np.where(a > 1 and a < 3)
print(i)
>> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我在a.any()a.all() in this other SO post上阅读,但这并不适用于我的目的,因为我希望所有符合条件的索引而不是单个布尔值

有两种方法可以适应这种情况吗?

1 个答案:

答案 0 :(得分:4)

使用np.where((a > 1) & (a < 3))