如何在numpy中将布尔数组转换为索引数组

Ric*_*ich 63 python arrays numpy

是否有一个有效的Numpy机制来检索基于条件为true的数组中位置的整数索引,而不是布尔掩码数组?

例如:

x=np.array([range(100,1,-1)])
#generate a mask to find all values that are a power of 2
mask=x&(x-1)==0
#This will tell me those values
print x[mask]
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我想知道指标imask地方mask[i]==True.是否有可能在没有循环的情况下生成这些?

Ste*_*joa 69

另外一个选项:

In [13]: numpy.where(mask)
Out[13]: (array([36, 68, 84, 92, 96, 98]),)
Run Code Online (Sandbox Code Playgroud)

这是一回事numpy.where(mask==True).

  • 或者类似地,如果你总是有一维数组:`numpy.flatnonzero(mask)` (4认同)

aga*_*rs3 28

您应该可以使用它numpy.nonzero()来查找此信息.

  • @FloridaMan:“ numpy.nonzero”没有给出带有值数组的元组作为第二个组件。如果布尔数组是多维的,则使用元组。从文档中:“返回一个数组元组,每个维[…]一个。” (2认同)