Numpy Tutorial - Boolean Indexing

A quick look at the reading tutorial, I cannot understand this sentence.

a = np.arange(12).reshape(3,4)
b1 = np.array([False,True,True]) 
b2 = np.array([True,False,True,False])
>>> a[b1,b2]  
array([ 4, 10])

Why a[b1,b2]eat array([4,10])instead array([[4,6],[8,10]])?

+4
source share
1 answer

This is because you are doing integer array indexing.

Indices are computed from Boolean arrays -

In [72]: idx1 = np.flatnonzero(b1)

In [73]: idx2 = np.flatnonzero(b2)

In [75]: idx1
Out[75]: array([1, 2])

In [76]: idx2
Out[76]: array([0, 2])

Then the indexing of the integer array is performed for each group of indices using each element from the indexing arrays -

In [77]: a[1,0] # 1 from idx1[0], 0 from idx2[0]
Out[77]: 4

In [78]: a[2,2] # 2 from idx1[1], 2 from idx2[1]
Out[78]: 10

To achieve this extraction of blocks in MATLAB style, we need to use open arrays and indexes in each of these axes / dull. To create such open arrays in NumPy, np.ix_-

In [89]: np.ix_(b1,b2)
Out[89]: 
(array([[1],
        [2]]), array([[0, 2]]))

In [90]: a[np.ix_(b1,b2)]
Out[90]: 
array([[ 4,  6],
       [ 8, 10]])
+5
source

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


All Articles