[Numpy-discussion] Indexing changes/deprecations

Sebastian Berg sebastian at sipsolutions.net
Fri Sep 27 12:36:44 EDT 2013


On Fri, 2013-09-27 at 08:45 -0700, Jaime Fernández del Río wrote:
> 
> 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])
> 
I agree that this can be confusing, but I think the fancy indexing logic
(plus the "boolean is much like a nonzero(boolean) call") dictates this.

One could think about doing something here, but it would basically
require a secondary indexing mechanism  like
`arr.no_broadcast_fancy[index]`.

`np.ix_` currently implements a conversion logic for this, though it
cannot support slices.

> 
> 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

In [11]: a[np.ix_(row_idx, col_idx)]
Out[11]: 
array([[1, 2, 3],
       [5, 6, 7]])


<snip>
> 

However, there is one further point here that I think is likely worth
changing. And that is adding a check that the boolean array has the
correct shape. The `nonzero` logic works good, but it allows things
like:

np.array([1, 2])[np.array([True, False, False, False])]

Which is a bit weird, though maybe not harmful.

- Sebastian

> Jaime
> 
> 
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion





More information about the NumPy-Discussion mailing list