简体   繁体   English

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

[英]Indexing with boolean arrays into multidimensional arrays using numpy

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! 谢谢!

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. 如您所见,这相当于上面显示的i1i2 Hence, a[b1,b2] will have the same result. 因此, a[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). 另请注意,上述操作仅可能,因为b1b2都具有相同数量的True值(因此,它们表示以整数形式表示的两个相同长度的数组)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM