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

为君一笑 提交于 2020-02-03 10:02:50

问题


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

回答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.




回答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



来源:https://stackoverflow.com/questions/47919869/is-there-a-canonical-way-of-obtaining-a-0d-numpy-subarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!