0
我可以得到numpy.where()
爲一個條件,但不是兩個條件。這個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讀了,但這並不爲我的目的,因爲我的工作希望所有符合條件的索引而不是單個布爾值。
有兩種方法適應這種情況嗎?
當你在一個標量上下文中使用一個布爾數組像'if',或在這種情況下,Python的'和'這個值誤差產生的。改用'&'。並用'()'控制操作符的順序。 – hpaulj