简体   繁体   English

当len <ndim时,使用元组(或列表)为numpy数组建立索引?

[英]Index a numpy array using a tuple (or list) when len < ndim?

I have a 3d numpy array, eg: 我有一个3D的numpy数组,例如:

>>> A = np.arange(24).reshape(2,3,4)

I want to take a 1d slice along axis 0 based on a pair of coordinates for axes 1 and 2: 我想基于轴1和2的一对坐标沿轴0​​取一维切片:

>>> h = 1
>>> l = 2
>>> A[:,h,l]
array([ 6, 18])

So far so good. 到现在为止还挺好。 But what if my coordinate pair is stored as a tuple or a list, rather than two integers? 但是,如果我的坐标对存储为元组或列表而不是两个整数,该怎么办? I've experimented with a few obvious options, to no avail: 我已经尝试了一些明显的选择,但没有成功:

>>> coords = (1,2)
>>> A[coords]
array([20, 21, 22, 23])
>>> A[:,coords]
array([[[ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[16, 17, 18, 19],
        [20, 21, 22, 23]]])
>>> A[...,coords]
array([[[ 1,  2],
        [ 5,  6],
        [ 9, 10]],

       [[13, 14],
        [17, 18],
        [21, 22]]])

I've googled around on this and not found anything, but it's entirely possible that I'm not searching with the appropriate jargon. 我已经对此进行了搜索,但没有发现任何东西,但是很可能我没有使用适当的术语进行搜索。 So, apologies if this is an overly simplistic question! 因此,如果这是一个过于简单的问题,我们深表歉意!

You can construct the slice tuple directly, with something like: 您可以使用以下方法直接构建切片元组:

In [11]: A[(slice(None),) + coords]
Out[11]: array([ 6, 18])

This is because calling A[:, 1, 2] is equivalent / calls: 这是因为调用A[:, 1, 2]等效于/调用:

In [12]: A.__getitem__((slice(None, None, None), 1, 2))
Out[12]: array([ 6, 18])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM