如何从NumPy中的索引数组创建布尔数组? [英] How to create a Boolean array from an array of indices in numpy?

查看:0
本文介绍了如何从NumPy中的索引数组创建布尔数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个多维索引数组,如何从这些索引创建布尔数组?对于一维情况,它将如下所示:

a = [1,5,6]
b = somefunction(total_array_length=10, a)
>>> [False, True, False, False, False, True, True, False, False, False]

对于2D情况,它将如下所示:

a = [[1,3],[4,2]]
b = somefunction(total_array_length=5, a)
>>> [[False, True, False, True, False], [False, False, True, False, True]]

我想使用它为数组创建掩码。我有一个8维的多维数组,对于最后一个轴,我可以找到我想要保留的元素的索引。换句话说,我有一个8维数组,其中最后一个轴包含我想要保留在原始数组中的所有索引。有人知道怎么做吗?

在上面的函数中,total_array_length将等于原始数组的长度。

那么,如何对具有索引形状数组(23,5,76,32,1,3,8,4)的形状数组(23,5,76,32,1,3,8,4)执行此操作?注4<;9但除此之外,它具有相同的尺寸。

a.shape = (23,5,76,32,1,3,8,4) 
b = somefunction(total_array_length=9, a)
b.shape =(23,5,76,32,1,3,8,9) 

推荐答案

第一种情况:

In [23]: a = [1,5,6]
In [24]: b = np.zeros(10, dtype=bool)
In [25]: b[a] = True
In [26]: b
Out[26]: array([False,  True, False, False, False,  True,  True, False, False, False], dtype=bool)

同样简单但尽可能快的列表版本:

In [27]: [True if i in a else False for i in range(10)]
Out[27]: [False, True, False, False, False, True, True, False, False, False]

对于列表,只需嵌套列表理解:

In [34]: [[True if i in a1 else False for i in range(5)] for a1 in a]
Out[34]: [[False, True, False, True, False], [False, False, True, False, True]]

第二种情况的数组版本为:

In [41]: a = [[1,3],[4,2]]
In [42]: b = np.zeros((len(a),5), bool)
In [43]: b[[[0],[1]],a]
Out[43]: 
array([[False, False],
       [False, False]], dtype=bool)
In [44]: b[[[0],[1]],a]=True
In [45]: b
Out[45]: 
array([[False,  True, False,  True, False],
       [False, False,  True, False,  True]], dtype=bool)
然而,只有当a的子列表都相同长度时,这才能起作用。如果他们不同,我认为我们将不得不用一个扁平化的版本。实际上,将2D案例转变为原始的1D案例。


对于参差不齐的a,列表版本还是很容易的:

In [49]: a = [[1,2,3],[4,2],[1]]
In [50]: [[True if i in a1 else False for i in range(5)] for a1 in a]
Out[50]: 
[[False, True, True, True, False],
 [False, False, True, False, True],
 [False, True, False, False, False]]

但数组版本比较复杂:

为行和列构造两个索引数组:

In [53]: a0 = np.repeat(np.arange(3),[len(i) for i in a])
In [54]: a0
Out[54]: array([0, 0, 0, 1, 1, 2])
In [55]: a1 = np.hstack(a)
In [56]: a1
Out[56]: array([1, 2, 3, 4, 2, 1])

获取等效的Raved(1维)索引:

In [57]: np.ravel_multi_index((a0,a1),(3,5))
Out[57]: array([ 1,  2,  3,  9,  7, 11], dtype=int32)

通过flat将其应用于二维数组:

In [58]: b = np.zeros((3,5),bool)
In [59]: b.flat[Out[57]] = True
In [60]: b
Out[60]: 
array([[False,  True,  True,  True, False],
       [False, False,  True, False,  True],
       [False,  True, False, False, False]], dtype=bool)

这篇关于如何从NumPy中的索引数组创建布尔数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆