Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

Not sure I understood properly what you want, does this look clean enough?

In [1]: import numpy as np

In [2]: a = np.random.randint(0,4,(2,3,4))
   ...: idx = (1,1,1)
   ...: 

In [3]: a[idx]
Out[3]: 2

In [4]: a[idx][...]
Out[4]: array(2)

EDIT: note that this returns a copy, not a 0D view of the same array

Post a Comment for "Is There A Canonical Way Of Obtaining A 0d Numpy Subarray?"