我可以让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上阅读,但这并不适用于我的目的,因为我希望所有符合条件的索引而不是单个布尔值
有两种方法可以适应这种情况吗?
答案 0 :(得分:4)
使用np.where((a > 1) & (a < 3))