I would have expected True to preserve a ndarray when used as a mask, however, it adds a dimension, just like None.
arr = np.arange(16).reshape(2, 4, 2)
np.all(arr[True] == arr) # outputs: True
Close enough, however looking closer:
arr[True].shape # outputs: (1, 2, 4, 2)
arr[None].shape # outputs: (1, 2, 4, 2)
I found two ways to set an identity mask: using slice(None) or Ellipsis.
np.all(arr[slice(None)] == arr) # outputs: True
arr[slice(None)].shape # outputs: (2, 4, 2)
np.all(Ellipsis == arr) # outputs: True
arr[Ellipsis].shape # outputs: (2, 4, 2)
Nothing really surprising here as this is how slicing works in the first place. slice(None) is a tad ugly and Ellipsis seems a wee bit faster.
However, going through:
I am not sure I fully understand this:
Deprecated since version 1.15.0: In order to remain backward compatible with a common usage in Numeric, basic slicing is also initiated if the selection object is any non-ndarray and non-tuple sequence (such as a list) containing slice objects, the Ellipsis object, or the newaxis object, but not for integer arrays or other embedded sequences.
I understand that the best way to preserve an array is not to mask it, but say I really want to setup a default value for a mask... ;-)
Question: Which is the preferred way to setup an identity mask ? And if I may, is True adding a dimension the intended behavior ?
For a sample 2d array:
A view with ellipsis:
A view with an added dimension:
A copy with an added dimension - note the change data address. Advanced indexing.
Another copy with a size 0 dimension. It's reusing memory.
The only applicable reference in the
indexingpage that I can find is:https://numpy.org/doc/stable/reference/arrays.indexing.html#detailed-notes
I wouldn't be surprised if this behavior was a left over from some past implementation. Due a history of merging several numeric packages, there are some rough edges. Some of those have been, or are in the process of, deprecation.
A scalar boolean index is a
zero dimensional boolean array:We can add the new dimension else where: