简体   繁体   English

部分索引多维数组

[英]Indexing a multi-dimensional array partially

import numpy as np
arr = np.random.rand(50,3,3,3,16)
ids = (0,0,2,10)
b = arr[:, ids]  # don't work
b = arr[:, *ids]  # don't work
b = arr[:][ids]  # don't work
b = arr[:, tuple(ids)]  # don't work
b = arr[: + ids]  # don't work, obviously..
# b = arr[:,0,0,2,10].shape  # works (desired outcome)

I know there have been several questions about this, like Tuple as index of multidimensional array or Unpacking tuples/arrays/lists as indices for Numpy Arrays but none of them work for my case. 我知道对此有几个问题,例如元组作为多维数组的索引,或者拆包元组/数组/列表作为Numpy数组的索引,但是它们都不适合我的情况。 Basically I want to index everything in the first axis, of specified "columns" in the rest of the axes (see the last line of my code). 基本上,我想在第一个轴上索引所有其余轴中指定的“列”中的所有内容(请参阅代码的最后一行)。 The desired output shape should be (50,) in this case. 在这种情况下(50,)所需的输出形状应为(50,)

But I want to index with a tuple/list of ids because I need to iterate through them, for example: 但是我想用元组/ ID列表建立索引,因为我需要遍历它们,例如:

all_ids = ((0,0,0,2), (0,0,0,6), (1,1,0,2), (1,1,0,6),
           (2,2,0,2), (2,2,0,6), (2,2,2,2), (2,2,2,6))
c = 0
for id in all_ids:
    c += arr[:, id].sum() 

Add slice(None) to first dimension in ids and then subset: slice(None)添加到ids第一维,然后添加子集:

arr[(slice(None),) + ids].shape
# (50,)

where: 哪里:

(slice(None),) + ids
# (slice(None, None, None), 0, 0, 2, 10)

Notice slice(None, None, None) is equivalent to : , ie slice all. 注意slice(None, None, None)等效于: ,即全部切片。 You can read docs on using slice object for indexing here . 您可以在此处阅读有关使用slice对象进行索引的文档

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

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