[Numpy-discussion] Why does fancy indexing work like this?
Sebastian Berg
sebastian at sipsolutions.net
Wed Jul 22 18:31:58 EDT 2020
On Wed, 2020-07-22 at 16:23 -0600, Aaron Meurer wrote:
> Why does fancy indexing have this behavior?
>
> > > > a = np.empty((0, 1, 2))
> > > > b = np.empty((1, 1, 2))
> > > > a[np.array([10, 10])]
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> IndexError: index 10 is out of bounds for axis 0 with size 0
> > > > a[:, np.array([10, 10])]
> array([], shape=(0, 2, 2), dtype=float64)
> > > > a[:, :, np.array([10, 10])]
> array([], shape=(0, 1, 2), dtype=float64)
> > > > b[np.array([10, 10])]
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> IndexError: index 10 is out of bounds for axis 0 with size 1
> > > > b[:, np.array([10, 10])]
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> IndexError: index 10 is out of bounds for axis 1 with size 1
> > > > b[:, :, np.array([10, 10])]
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> IndexError: index 10 is out of bounds for axis 2 with size 2
>
> As far as I can tell, the behavior is that if an array has a 0
> dimension and an integer array index indexes an axis that isn't 0,
> there are no bounds checks. Why does it do this? It seems to be
> inconsistent with the behavior of shape () fancy indices (integer
> indices). I couldn't find any reference to this behavior in
> https://numpy.org/doc/stable/reference/arrays.indexing.html.
>
The reason is because we used to not do this when there are *two*
advanced indices:
arr = np.ones((5, 6))
arr[[], [10, 10]]
giving an empty result. If you check on master (and maybe on 1.19.x, I
am not sure). You should see that all of your examples give a
deprecation warning to be turned into an error (except the example I
gave above, which can be argued to be correct).
- Sebastian
> Aaron Meurer
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at python.org
> https://mail.python.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: This is a digitally signed message part
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20200722/89a51605/attachment.sig>
More information about the NumPy-Discussion
mailing list