numpy,不同的数组层的不同切片

时间:2017-01-17 13:37:12

标签: python arrays numpy vectorization

我有3d数组m*n*k,对于每个2d层我想要一个大小为i*j的子数组。我有一个数组c,每个图层的切片起始坐标的大小为2*k。有没有好的简单的方法来获得我需要的东西而没有任何循环?

示例:

test = np.arange(18).reshape((3,3,2))
c = np.array([[0,1], [0, 1]])

test[:,:,0] = array([[ 0,  2,  4],
                     [ 6,  8, 10],
                     [12, 14, 16]])

test[:,:,1] = array([[ 1,  3,  5],
                     [ 7,  9, 11],
                     [13, 15, 17]])

我想要一个数组

  [[[ 0,  9],
    [ 2,  11]],

   [[ 6,  15],
    [ 8,  17]]]

循环解决方案:

h=2
w=2
layers = 2
F = np.zeros((h,w,layers))
for k in range(layers):
    F[:,:,k] = test[c[0,k]:c[0,k]+h, c[1,k]:c[1,k]+w, k]

1 个答案:

答案 0 :(得分:1)

这是一种利用broadcastingadvanced-indexing -

的矢量化方法
d0,d1,d2 = np.ogrid[:h,:w,:layers]
out = test[d0+c[0],d1+c[1],d2]

示例运行 -

In [112]: test = np.arange(200).reshape((10,10,2))
     ...: c = np.array([[0,1], [0, 1]])
     ...: 

In [113]: h=4
     ...: w=5
     ...: layers = 2
     ...: F = np.zeros((h,w,layers))
     ...: for k in range(layers):
     ...:     F[:,:,k] = test[c[0,k]:c[0,k]+h, c[1,k]:c[1,k]+w, k]
     ...:     

In [114]: d0,d1,d2 = np.ogrid[:h,:w,:layers]
     ...: out = test[d0+c[0],d1+c[1],d2]
     ...: 

In [115]: np.allclose(F, out)
Out[115]: True