我可以用掩码分割 numpy 数组吗?

JY *_*Won 6 python numpy python-3.x numpy-slicing numpy-ndarray

我想将数组拆分为带有掩码和索引的数组,
如下所示

a = array([ 0,  1,  2,  3,  4, 5]))  
b = [0,2,3]  
Run Code Online (Sandbox Code Playgroud)

进入

c = array([[0, 2, 3], [1, 3, 4], [2, 4, 5]])  
Run Code Online (Sandbox Code Playgroud)

我可以在没有循环的情况下执行此操作吗?

编辑:

更多例子...

说,我们有一个a形状的数组,[10, 10, 10]
其中a[x, y, :] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

现在给了面具 b = [0, 3, 7]

我希望输出是一个c具有形状的数组,[10, 10, 3, 3]
其中c[x, y, :, :] = [[0, 3, 7], [1, 4, 8], [2, 5, 9]]

Lud*_*igH 3

您可以生成b所需索引之间的广播总和以及移位向量。然后你可以再次广播成更大的尺寸。由于示例中的输出不依赖于数组a,因此我忽略了这一点。

from numpy import array, broadcast_to, arange
from numpy.random import random

a = random((10,10,10)) # not used on the code at all.... don't understand what it is for...

b = [0,2,3]
b_array = array(b)
b_shifts = arange(3).reshape(-1,1)
c_cell= b+b_shifts # here, they are broadcasted toegether. one is a row-vector and one is a column-vector...
c = broadcast_to(c_cell,(10,10,3,3))

Run Code Online (Sandbox Code Playgroud)

b_shifts您可能想根据步长等使用其他方法创建......


根据您的评论进行编辑 ,似乎更准确的答案是:

from numpy import array, arange
a = arange(2*2*10).reshape((2,2,10)) # some example input 
b = array([0,2,3])                   # the 'template' to extract
shifts = arange(3).reshape(-1,1)     # 3 is the number of repeats
indexer = b+shifts                   # broadcasted sum makes a matrix
c = a[:,:,indexer]                   # extract

Run Code Online (Sandbox Code Playgroud)

这会将b数组作为一种模板,并以一定的偏移重复它。最后,它会将每个数组中的这些条目提取a[i,j,:]c[i,j,:,:]. 上面的输出是:

print(a)

[[[ 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 27 28 29]
  [30 31 32 33 34 35 36 37 38 39]]]
Run Code Online (Sandbox Code Playgroud)

print(c)

[[[[ 0  2  3]
   [ 1  3  4]
   [ 2  4  5]]
  [[10 12 13]
   [11 13 14]
   [12 14 15]]]
 [[[20 22 23]
   [21 23 24]
   [22 24 25]]
  [[30 32 33]
   [31 33 34]
   [32 34 35]]]]
Run Code Online (Sandbox Code Playgroud)