简体   繁体   English

使用数组作为多维数组的索引掩码

[英]Use Array as Indexing Mask for Multidimensional Array

I have the following arrays:我有以下数组:

a = np.arange(12).reshape((2, 2, 3))

and

b = np.zeros((2, 2))

Now I want to use b to access a, st at each for index i,j we take the z-th element of a, if b[i, j] = z.现在我想使用 b 来访问 a, st 在每个索引 i,j 我们取 a 的第 z 个元素,如果 b[i, j] = z。 Meaning for the above example the answer should be [[0, 3], [6, 9]].对于上面的例子,答案应该是 [[0, 3], [6, 9]]。 I feel this is very related to np.choose, but yet somehow cannot quite manage it.我觉得这与 np.choose 非常相关,但不知何故无法完全管理它。 Can you help me?你能帮助我吗?

Two approaches could be suggested.可以建议两种方法。

With explicit range arrays for advanced-indexing -使用explicit范围数组进行advanced-indexing -

m,n = b.shape
out = a[np.arange(m)[:,None],np.arange(n),b.astype(int)]

With np.take_along_axis -随着np.take_along_axis -

np.take_along_axis(a,b.astype(int)[...,None],axis=2)[...,0]

Sample run -样品运行 -

In [44]: a
Out[44]: 
array([[[ 0,  1,  2],
        [ 3,  4,  5]],

       [[ 6,  7,  8],
        [ 9, 10, 11]]])

In [45]: b
Out[45]: 
array([[0., 0.],
       [0., 0.]])

In [46]: m,n = b.shape

In [47]: a[np.arange(m)[:,None],np.arange(n),b.astype(int)]
Out[47]: 
array([[0, 3],
       [6, 9]])

In [48]: np.take_along_axis(a,b.astype(int)[...,None],axis=2)[...,0]
Out[48]: 
array([[0, 3],
       [6, 9]])

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

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