[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
http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays
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:
>>> np.broadcast_arrays(y, b[:, 5])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.3/site-packages/numpy/lib/stride_tricks.py", line
94, in broadcast_arrays
"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?
Thanks in advance, regards
Juan Luis Cano
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20121117/620b3b61/attachment.html
More information about the SciPy-User
mailing list