[Numpy-discussion] What is up with raw boolean indices (like a[False])?

Aaron Meurer asmeurer at gmail.com
Mon Jul 6 15:27:17 EDT 2020


> Its fully intentional as it is the correct generalization from an N-D
> boolean index to include a 0-D boolean index.
> To be fair, there is a footnote in the "Detailed notes" saying that:
> "the nonzero equivalence for Boolean arrays does not hold for zero
> dimensional boolean arrays.", this is for technical reasons since
> `nonzero` does not do useful things for 0-D input.
>
> In any case, a boolean index always does the following:
> 1. It will *remove as many dimensions as the index has, because this
>    is the number of dimensions effectively indexed by it*
> 2. It will add a single new dimension at the same place.  The length of
>    this new dimension is the number of `True` elements.
> 3. If you have multiple advanced indexing you get annoying broadcasting
>    of all of these. That is *always* confusing for boolean indices.
>    0-D should not be too special there...
> And this generalizes to 0-D just as well, even if it may be a bit
> surprising at first.

I guess if those are the base rules for boolean indices this makes
sense. So that brings up the question then, is there a way to add
arbitrary empty dimensions using an index?

>
> I have written much of this more clearly once before in this NEP, which
> may be a good read to _really_ understand it:
> https://numpy.org/neps/nep-0021-advanced-indexing.html
> In general, I wonder if going into much depth about how 0-D arrays are
> not actually really handled very special is good.  Yes, its confusing
> on its own, but it seems also a bit like overloading the user with
> unnecessary knowledge?

The page I referenced is already written like a very highly technical
document, so I think it should embrace that and fully describe the
spec of NumPy indexing. NumPy could use more user-friendly
documentation for indexing, but that page ain't it. FWIW, I wrote some
documentation on slices of my own here
https://quansight.github.io/ndindex/slices.html. I eventually plan to
extend this to all forms of NumPy indexing. Anyway, the three bullet
points you mentioned above would be helpful to include in the docs.

> Cheers,
> Sebastian


More information about the NumPy-Discussion mailing list