Go Beyond
Go Beyond

Reputation: 138

Indexing with Boolean arrays

a = np.arange(12).reshape(3,4)

b1 = np.array([False,True,True]

b2 = np.array([True,False,True,False])

a[b1,b2]

output:

array([4,10])

I am not getting how it comes 4 and 10 in a[b1,b2]

Upvotes: 2

Views: 376

Answers (3)

NNN
NNN

Reputation: 593

The correct explanation is here. To summarize,

a[b1,b2] with boolean arrays b1 and b2 is equivalent to a[b1.nonzero(),b2.nonzero()].

nonzero() returns indices of True values. Therefore,

b1.nonzero()=(array([1, 2]),)
b2.nonzero()=(array([0, 2]),)

So, now, we're indexing with arrays. As with array based indexing, the [1,0]th element which is 4 and the [2,2]th element which is 10 is returned.

Upvotes: -2

Poe Dator
Poe Dator

Reputation: 4903

Apparently you expected to see array([[ 4, 6],[ 8, 10]]).

In boolean indexing NumPy returns only diagonal elements as described here:

without the np.ix_ call, only the diagonal elements would be selected(...). This difference is the most important thing to remember about indexing with multiple advanced indexes.

For the desired output use np.ix_():

a[np.ix_(b1,b2)]

Upvotes: 3

Dejene T.
Dejene T.

Reputation: 989

import numpy as np
a = np.arange(12).reshape(3, 4)
b1 = np.array([False,True,True])
b2 = np.array([True,False,True,False])
print(a)
print(a[b1, b2])

The first thing is that you have arranged 12 array elements which are starting with 0, step with 1, and stop with 12. And then you have reshaped your array elements with 3 rows and 4 columns. look like the following:

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

Then finally printing the array elements with row and column because the array is a two-dimensional array it has rows and columns.\ b1 is representing the rows of the elements which have three rows and the first row(row[0]) is False. The second row (row[1]) is True.... the last row(row[2]) is True. b2 also representing the columns of the array which has 4 columns. The first column(column[0]) is True...The third column(column[2]) is True. and The last is False. Then when we want to return the output of the two-dimensional array we use array name(a[b1, b2]), b1 and b2 are row index and column indexes.

The second row and the first column becomes True. therefore it returns 4. The others are False. And also the third row and column also become True. Therefore, it returns 10. The others are False.

This is what I understood. Sorry for my bad English.

Upvotes: 1

Related Questions