这种 numpy.where() 方法可以适用于两种情况而不是一种吗?
Can this numpy.where() approach be adapted for two conditions instead of one?
我可以让 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,但这对我的目的不起作用,因为我想要符合条件的所有索引而不是单个布尔值.
有没有办法让它适应两种情况?
使用np.where((a > 1) & (a < 3))
我可以让 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,但这对我的目的不起作用,因为我想要符合条件的所有索引而不是单个布尔值.
有没有办法让它适应两种情况?
使用np.where((a > 1) & (a < 3))