[Numpy-discussion] Indexing changes/deprecations
Jaime Fernández del Río
jaime.frio at gmail.com
Fri Sep 27 11:45:57 EDT 2013
On Fri, Sep 27, 2013 at 5:27 AM, Sebastian Berg
<sebastian at sipsolutions.net>wrote:
>
> And most importantly, is there any behaviour thing in the index
> machinery that is bugging you, which I may have forgotten until now?
>
I find this behavior of boolean indexing a little bit annoying:
>>> a = np.arange(12).reshape(3, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> row_idx = np.array([True, True, False])
>>> col_idx = np.array([False, True, True, False])
This shouldn't work, but it does, because there are the same number of
Trues in both indexing arrays. Do we really want this to happen?:
>>> a[row_idx, col_idx]
array([1, 6])
This shouldn't work, and it doesn't:
>>> col_idx = np.array([False, True, True, True])
>>> a[row_idx, col_idx]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape
It would be nice if something like this worked, or at least it should raise
a different error, because those arrays **can** be broadcast to a single
shape:
>>> a[row_idx[:, np.newaxis], col_idx]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape
For this there is the following workaround, although it does creation of a
fully expanded boolean indexing array, which I was hoping the previous
non-working code would avoid:
>>> a[row_idx[:, np.newaxis] & col_idx]
array([1, 2, 3, 5, 6, 7])
Jaime
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20130927/833b12e2/attachment.html>
More information about the NumPy-Discussion
mailing list