Python Numpy:通过z索引数组索引3d数组

Python Numpy:通过z索引数组索引3d数组,python,numpy,indexing,Python,Numpy,Indexing,假设我有一个数组 a = np.zeros((3, 3, 3)) 和一个z索引数组 z = np.random.randint(0, 3, (3, 3)) 说z是 array([[1, 0, 2], [2, 2, 1], [1, 1, 0]]) 现在我想选择a的值,坐标从z的左上角开始,沿行遍历数组。列方式也可以。0, 0, 1, 0, 1, 0, 0, 2, 2, ... . 粗体值来自z数组 我想这正是你想要的 import numpy as np a

假设我有一个数组

a = np.zeros((3, 3, 3))
和一个z索引数组

z = np.random.randint(0, 3, (3, 3))
说z是

array([[1, 0, 2],
       [2, 2, 1],
       [1, 1, 0]])

现在我想选择a的值,坐标从z的左上角开始,沿行遍历数组。列方式也可以。0, 0, 1, 0, 1, 0, 0, 2, 2, ... . 粗体值来自z数组

我想这正是你想要的

import numpy as np 

a = np.arange(3*3*3).reshape(3,3,3)
z = np.array([[1, 0, 2],
       [2, 2, 1],
       [1, 1, 0]])
i = np.arange(a.shape[0]).repeat(a.shape[0]).reshape(a.shape[0], a.shape[1])
j = i.T
#Should do the same as this. possible more efficient, did not test.
#i, j = np.indices(a[...,0].shape)
print a[i,j,z]

a应该是3d阵列吗?是的,对不起。修好了,没有。如果我使用零,然后a[I,j,z]=1,a[0,0,0]是1,但应该是0。如果我是数组[[0,0,0],[1,1,1],[2,2,2]],并且j是I.T,它就可以工作。