Numpy索引 - 使用一个解开的索引进行基本索引

问题描述 投票:0回答:1

如果我有以下4D数组:

mat = np.array(np.arange(27)).reshape((3,3,3))
[[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]]

 [[ 9 10 11]
  [12 13 14]
  [15 16 17]]

 [[18 19 20]
  [21 22 23]
  [24 25 26]]]

以及以下解开的指数:

ind = np.unravel_index([7], mat.shape[1:])
(array([2], dtype=int64), array([1], dtype=int64))

什么是最好的访问方式

mat[:, 2, 1]
[ 7 16 25]

使用解开的索引?我正在寻找这个问题的通用解决方案,其中mat的维数可以变化。

我知道我可以这样做:

new_ind = (np.arange(mat.shape[0]),) +  ind
mat[new_ind]
[ 7 16 25]

但我想知道是否有办法做到这一点,不需要明确建立一个新的索引?

python numpy
1个回答
2
投票

您需要构建一个新的索引元组:

In [8]: ind=np.unravel_index([7,8],(3,3))                                       
In [9]: ind                                                                     
Out[9]: (array([2, 2]), array([1, 2]))
In [10]: (slice(None),*ind)                                                     
Out[10]: (slice(None, None, None), array([2, 2]), array([1, 2]))
In [11]: np.arange(27).reshape(3,3,3)[_]                                        
Out[11]: 
array([[ 7,  8],
       [16, 17],
       [25, 26]])

Out[10]相当于在你的解体指数中加入:

In [12]: np.s_[:,[2,2],[1,2]]                                                   
Out[12]: (slice(None, None, None), [2, 2], [1, 2])
© www.soinside.com 2019 - 2024. All rights reserved.