从布尔数组中获取索引到列表

时间:2017-03-29 23:10:23

标签: python arrays indexing boolean

我有一个名为TorF -True或False-的数组,它是一个布尔数组。说它是一个10 x 10阵列,有各种各样的真主和法尔斯。如何获取所有True元素的索引?

在一维数组上,我看到np.where()效果很好。在我的10x10阵列上,我可以使用np.where(TorF [0])并完美地返回第一行的索引。我可以手动为第二行执行np.where(TorF [1])。

我想为所有10行或更大的数组执行此操作直到" N"行。问题是每行的True元素数量不同。因此,True元素索引列表可能如下所示:

[0, 7, 9]  #the first, eighth, and tenth elements were True
[1, 4, 5, 8, 9]  #2nd, 5th, 6th, 9th, and 10th elements were True
[2, 6]
[0, 5, 7]
etc. up to ten lists or "N" lists

由于索引列表长度不同,我有问题。如何创建循环以获取True索引列表?或者是否有更好的功能来返回此列表?理想情况下,我希望有一个名为TrueList的变量来保存这10个子集。

1 个答案:

答案 0 :(得分:0)

最简单的方法是在另一个列表理解中使用列表和列表理解:

>>> arr = np.random.randint(0, 2, (10, 10)).astype(bool)
>>> [[idx for idx, item in enumerate(subarr) if item] for subarr in arr.tolist()]
[[0, 5, 7, 8],
 [2, 3, 4, 5, 6, 8, 9],
 [0, 3, 4, 9],
 [1, 3, 4, 5, 6, 9],
 [0, 1, 2, 4, 5, 7],
 [0, 7, 9],
 [0, 5, 8, 9],
 [1, 5, 7],
 [3, 6],
 [0, 1, 2, 4, 5, 6, 7, 9]]

对于使用python迭代的小数组甚至可以比像np.where这样的numpy函数更快,所以当你处理10x10数组时,列表推导的性能可以相提并论。但是当然你也可以在列表理解中使用np.where

>>> [np.where(subarr)[0] for subarr in arr]
[array([0, 5, 7, 8], dtype=int64),
 array([2, 3, 4, 5, 6, 8, 9], dtype=int64),
 array([0, 3, 4, 9], dtype=int64),
 array([1, 3, 4, 5, 6, 9], dtype=int64),
 array([0, 1, 2, 4, 5, 7], dtype=int64),
 array([0, 7, 9], dtype=int64),
 array([0, 5, 8, 9], dtype=int64),
 array([1, 5, 7], dtype=int64),
 array([3, 6], dtype=int64),
 array([0, 1, 2, 4, 5, 6, 7, 9], dtype=int64)]