Use np.where
获取给定条件的索引True
.
例子:
对于 2Dnp.ndarray
called a
:
i, j = np.where(a == value) # when comparing arrays of integers
i, j = np.where(np.isclose(a, value)) # when comparing floating-point arrays
对于一维数组:
i, = np.where(a == value) # integers
i, = np.where(np.isclose(a, value)) # floating-point
请注意,这也适用于以下条件>=
, <=
, !=
等等...
您还可以创建一个子类np.ndarray
与index()
method:
class myarray(np.ndarray):
def __new__(cls, *args, **kwargs):
return np.array(*args, **kwargs).view(myarray)
def index(self, value):
return np.where(self == value)
Testing:
a = myarray([1,2,3,4,4,4,5,6,4,4,4])
a.index(4)
#(array([ 3, 4, 5, 8, 9, 10]),)