Adding a numpy array with booleans

Can someone explain what this code is doing?

a = np.array([[1, 2], [3, 4]]) a[..., [True, False]] 

What does [True, False] do there?

+5
source share
1 answer

Ellipsis notation and logical values โ€‹โ€‹as integers

From the numpy doc :

The ellipsis expands to the number of: objects needed to create a selection tuple of the same length as x.ndim. Only one ellipse can be present.

True and False just confusing 0 and 1 . Taking an example from the docs:

 x = np.array([[[1],[2],[3]], [[4],[5],[6]]]) x[...,0] # outputs: array([[1, 2, 3], # [4, 5, 6]]) x[..., False] # same thing 

Boolean values โ€‹โ€‹indicate an index, as do numbers 0 or 1.


In response to your question in the comments

At first it seems magical that

 a = np.array([[1, 2], [3, 4]]) a[..., [True, True]] # = [[2,2],[4,4]] 

But when we consider it as

 a[..., [1,1]] # = [[2,2],[4,4]] 

Seems less impressive.

Similarly:

 b = array([[1,2,3],[4,5,6]]) b[...,[2,2]] # = [[3,3],[5,5]] 

After applying the ellipsis rules; true and false capture column indices, same as 0, 1 or 17, would have


Logical arrays for complex indexing

There are some subtle differences (bool has a different type than ints). Many hairy details can be found here . They don't seem to have any roll in your code, but they are interesting in determining how numpy indexing works.

In particular, this line is probably what you are looking for:

In the future, Boolean array-likes (e.g. python bools lists) will always be considered boolean indexes

On this page, they talk about boolean arrays , which are quite complex as an indexing tool.

Boolean arrays used as indexes are processed differently in different ways than index arrays. Boolean arrays should have the same shape as the initial sizes of the indexed array

Transition down a little

Unlike massive index arrays, in the Boolean case, the result is a 1-D array containing all the elements in the indexed array corresponding to all true elements in the Boolean array. elements in an indexed array are always repeated and returned in a row (C-style). The result is also identical in [np.nonzero (b)]. As is the case with index arrays, it returns what the data is, not the view as you get the fragments.

+1
source

All Articles