# [SciPy-User] Question about boolean indexing in NumPy

Juan Luis Cano Rodríguez juanlu001@gmail....
Sat Nov 17 04:19:52 CST 2012

```Hello everybody, I was trying to understand the use of boolean indexing in
NumPy, and looking both in the User Guide and the Reference has driven me a
bit confused.

On the one hand, in the User Guide

is stated that "Boolean arrays must be [...] broadcastable to the same
shape", and then you have this example:

>>> y = np.arange(35).reshape(5,7)
>>> b = y > 20
>>> b[:,5] # use a 1-D boolean that broadcasts with y
array([False, False, False,  True,  True], dtype=bool)
>>> y[b[:,5]]
array([[21, 22, 23, 24, 25, 26, 27],
[28, 29, 30, 31, 32, 33, 34]])

but, indeed, these two arrays don't broadcast! Though they do if you
transpose one of them:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.3/site-packages/numpy/lib/stride_tricks.py", line
"incompatible dimensions on axis %r." % (axis,))
ValueError: shape mismatch: two or more arrays have incompatible dimensions
on axis 1.

On the other hand, it is also stated that "Boolean arrays must be of the
same shape as the array being indexed", but indeed this is not true,
because according to the reference guide

http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#boolean

"This advanced indexing [...] is always equivalent to [...]
x[obj.nonzero()]". So I can come up with an example:

>>> y[0, :]
array([0, 1, 2, 3, 4, 5, 6])
>>> y[0, :].shape
(7,)
>>> np.array([True, False, True, False]).shape  # Not the same shape!
(4,)
>>> y[0, :][np.array([True, False, True, False])]  # But actually it works
-> [].nonzero()
array([0, 2])

Is there anything that I am misunderstanding? Can everyone shine the light
on me in this topic?