Indexing with Boolean arrays to multidimensional arrays using numpy

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

The preliminary tutorial shows an 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 this is the last. Can anyone explain this to me?

Thanks!

+6
source share
1 answer

Your array consists of:

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

One way to index is to use a list of integers, specifying which rows / columns to include:

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

Value: row 1 column 0, row 2 column 2

When you use logical indexes, you specify which rows / columns to include and which:

 >>> 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 i1 and i2 shown above. Therefore, a[b1,b2] will have the same result.

Please also note that the above operation is possible only because both b1 and b2 have the same number of True values ​​(therefore, they are two arrays of the same length, expressed in integer form).

+4
source

Source: https://habr.com/ru/post/911717/


All Articles