Python获取3d数组的子数组

2024-04-23 21:07:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到一个三维阵列的多个子阵列。我可以在二维情况下使用堆栈后的函数拆分数组:

def blockshaped(arr, nrows, ncols):
    h, w = arr.shape
    return (arr.reshape(h//nrows, nrows, -1, ncols)
               .swapaxes(1,2)
               .reshape(-1, nrows, ncols))

所以我想把它扩展到3D数组的情况下,把块作为2D数组,但在第一维的每个切片中。我试着用一个“for循环”,但没用。。。在

例如:

^{pr2}$

我得到了4个“子阵列”:

array([[[ 2.,  1.],
        [ 1.,  1.]],

       [[ 1.,  1.],
        [ 1.,  1.]],

       [[ 3.,  1.],
        [ 1.,  1.]],

       [[ 1.,  1.],
        [ 1.,  1.]]])

但对于作为输入的三维阵列:

test2=np.array([[[ 2.,  1.,  1., 1.],
        [ 1.,  1.,  1., 1.],
        [ 3.,  1.,  1., 1.],
        [ 1.,  1.,  1., 1.]],

       [[ 5.,  1.,  1., 1.],
        [ 1.,  1.,  1., 1.],
        [ 2.,  1.,  1., 1.],
        [ 1.,  1.,  1., 1.]]])       

所以在这里我想要同样的分解但是在2个“切片”。。。在

def blockshaped(arr, nrows, ncols): 

    h, w, t = arr.shape 
    return (arr.reshape(h//nrows, nrows, -1, ncols)
               .swapaxes(1,2)
               .reshape(-1, nrows, ncols))

我尝试使用“for循环”,但不起作用:

for i in range(test2.shape[0]):                     
    sub = blockshaped(test[i,:,:], 2, 2)

Tags: forreturndef情况切片数组arrayarr