Search code examples
pythonarraysnumpymatrix-indexing

Is there a canonical way of obtaining a 0D numpy subarray?


Given a numpy ndarray and an index:

a = np.random.randint(0,4,(2,3,4))
idx = (1,1,1)

is there a clean way of retrieving the 0D subarray of a at idx?

Something equivalent to

a[idx + (None,)].squeeze()

but less hackish?

Note that @filippo's clever

a[idx][...]

is not equivalent. First, it doesn't work for object arrays. But more seriously it does not return a subarray but a new array:

b = a[idx][...]
b[()] = 7
a[idx] == 7
# False

Solution

  • b = a[idx+(Ellipsis,)]
    

    I'm testing on one machine and writing this a tablet, so can't give my usual verification code.

    Perhaps the best documentation explanation (or statement of fact) is:

    https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#detailed-notes

    When an ellipsis (...) is present but has no size (i.e. replaces zero :) the result will still always be an array. A view if no advanced index is present, otherwise a copy.