首页 > 解决方案 > 如何索引 3d 数组

问题描述

这个问题在这里已经有了答案:Index n dimensional array with (n-1) d array 1 answer

我认为这里的答案更直接(我马上就明白了这个问题)。重复的帖子很棒,我将它们与一个常见的索引功能联系起来,但我需要时间来理解。

我想通过我沿轴查询的索引从 3d 数组中提取数据,但我不知道如何编写它。

#data:
arr= np.array([[[ 0.000,  0.200],
                [ 0.000,  0.100],
                [-0.932, -0.073]],

               [[ 0.000,  0.000],
                [-0.932, -0.073],
                [-1.626, -0.900]],

               [[-0.132, -0.073],
                [-1.626, -0.900],
                [-1.802, -0.688]],

               [[-1.626, -0.900],
                [-1.802, -0.688],
                [-3.059, -1.190]]])

# This is the index
idx= np.array([[0, 1],
               [1, 2],
               [0, 0],
               [0, 1]])

# Expected output
    array([[ 0.000,  0.100],
           [-0.932, -0.900],
           [-0.132, -0.073],
           [-1.626, -0.688],

# If it is 2d it is like this:
axis=0:
arr[idx,np.arange(arr.shape[1])]
axis=1:
arr[np.arange(arr.shape[0]),idx]

但是不知道怎么写在3d数组上,希望能得到帮助。谢谢你。

标签: numpy

解决方案


您不太清楚idx适用于哪个轴。我有匹配的值来查看模式。

无论如何,这是索引

In [88]: arr[np.arange(4)[:,None], idx, np.arange(2)]
Out[88]: 
array([[ 0.   ,  0.1  ],
       [-0.932, -0.9  ],
       [-0.132, -0.073],
       [-1.626, -0.688]])

编写了 2 个范围,因此它们广播到与 相同的 (4,2) 形状idx


推荐阅读