The Python Oracle

numpy: broadcasting ndarray of booleans

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 Numpy: Broadcasting Ndarray Of Booleans
00:52 Accepted Answer Score 5
01:41 Thank you

--

Full question
https://stackoverflow.com/questions/1991...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #numpy

#avk47



ACCEPTED ANSWER

Score 5


The rules for so-called "fancing indexing" are detailed here. In particular, when the index, obj, is a NumPy array of dtype bool, x[obj]

... is always equivalent to (but faster than) x[obj.nonzero()] where, as described above, obj.nonzero() returns a tuple (of length obj.ndim) of integer index arrays showing the True elements of obj.

Since,

In [4]: a.nonzero()
Out[4]: (array([0]), array([0]))

b[a] is equivalent to b[a.nonzero()] which is

In [6]: b[(np.array([0]), np.array([0]))]
Out[6]: array([1])
In [7]: b[a]
Out[7]: array([1])

If you want to use a boolean array a to select rows of b, then, as Joran Beasley states, just keep a as a 1-dimensional boolean array:

import numpy as np

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