numpy: broadcasting ndarray of booleans
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Light Drops
--
Chapters
00:00 Question
01:08 Accepted answer (Score 5)
02:16 Thank you
--
Full question
https://stackoverflow.com/questions/1991...
Accepted answer links:
[detailed here]: http://docs.scipy.org/numpy/docs/numpy-d...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #numpy
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Light Drops
--
Chapters
00:00 Question
01:08 Accepted answer (Score 5)
02:16 Thank you
--
Full question
https://stackoverflow.com/questions/1991...
Accepted answer links:
[detailed here]: http://docs.scipy.org/numpy/docs/numpy-d...
--
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]]