使用numpy将布尔数组索引到多维数组中

时间:2023-01-18 21:22:07

I am new to using numpy and one thing that I really don't understand is indexing arrays.

我是新手使用numpy和一件我真正不理解的是索引数组。

In the tentative tutorial there is this example:

在暂定教程中有这个例子:

>>> a = arange(12).reshape(3,4)
>>> b1 = array([False,True,True])             # first dim selection
>>> b2 = array([True,False,True,False])       # second dim selection
>>>
>>> a[b1,b2]                                  # a weird thing to do
array([ 4, 10])

I have no idea why it does that last thing. Can anyone explain that to me?

我不知道它为什么会这么做。任何人都可以向我解释一下吗?

Thanks!

1 个解决方案

#1


5  

Your array consists of:

您的数组包括:

0  1  2  3
4  5  6  7
8  9 10 11

One way of indexing it would be using a list of integers, specifying which rows/columns to include:

索引它的一种方法是使用整数列表,指定要包含的行/列:

>>> i1 = [1,2]
>>> i2 = [0,2]
>>> a[i1,i2]
array([ 4, 10])

Meaning: row 1 column 0, row 2 column 2

含义:第1行第0列,第2列第2列

When you're using boolean indices, you're telling which rows/columns to include and which ones not to:

当您使用布尔索引时,您要告知要包含哪些行/列以及哪些不包括:

>>> b1 = [False,True,True]       # 0:no,  1:yes, 2:yes       ==> [1,2]
>>> b2 = [True,False,True,False] # 0:yes, 1:no,  2:yes, 3:no ==> [0,2]

As you can see, this is equivalent to the i1 and i2 shown above. Hence, a[b1,b2] will have the same result.

如您所见,这相当于上面显示的i1和i2。因此,[b1,b2]将具有相同的结果。

Note also that the operation above is only possible because both b1 and b2 have the same number of True values (so, they represent two arrays of the same length when expressed in the integer form).

另请注意,上述操作仅可能,因为b1和b2都具有相同数量的True值(因此,它们表示以整数形式表示的两个相同长度的数组)。

#1


5  

Your array consists of:

您的数组包括:

0  1  2  3
4  5  6  7
8  9 10 11

One way of indexing it would be using a list of integers, specifying which rows/columns to include:

索引它的一种方法是使用整数列表,指定要包含的行/列:

>>> i1 = [1,2]
>>> i2 = [0,2]
>>> a[i1,i2]
array([ 4, 10])

Meaning: row 1 column 0, row 2 column 2

含义:第1行第0列,第2列第2列

When you're using boolean indices, you're telling which rows/columns to include and which ones not to:

当您使用布尔索引时,您要告知要包含哪些行/列以及哪些不包括:

>>> b1 = [False,True,True]       # 0:no,  1:yes, 2:yes       ==> [1,2]
>>> b2 = [True,False,True,False] # 0:yes, 1:no,  2:yes, 3:no ==> [0,2]

As you can see, this is equivalent to the i1 and i2 shown above. Hence, a[b1,b2] will have the same result.

如您所见,这相当于上面显示的i1和i2。因此,[b1,b2]将具有相同的结果。

Note also that the operation above is only possible because both b1 and b2 have the same number of True values (so, they represent two arrays of the same length when expressed in the integer form).

另请注意,上述操作仅可能,因为b1和b2都具有相同数量的True值(因此,它们表示以整数形式表示的两个相同长度的数组)。