首页 > 解决方案 > How to reshape my 4D-np.array to a 2D matrix and keep the structure?

问题描述

Let's say I have an 4D np.array that consists of 4 groups of 4x4 matrices:

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

        [[2., 2.],
         [2., 2.]],

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

        [[4., 4.],
         [4., 4.]]],


       [[[5., 5.],
         [5., 5.]],

        [[6., 6.],
         [6., 6.]],

        [[7., 7.],
         [7., 7.]],

        [[8., 8.],
         [8., 8.]]],


       [[[9., 9.],
         [9., 9.]],

        [[10., 10.],
         [10., 10.]],

        [[11., 11.],
         [11., 11.]],

        [[12., 12.],
         [12., 12.]]],


       [[[13., 13.],
         [13., 13.]],

        [[14., 14.],
         [14., 14.]],

        [[15., 15.],
         [15., 15.]],

        [[16., 16.],
         [16., 16.]]]])

Now I want to reshape it to a single matrix so that I can have the groups in rows (but only the values, not as a matrix). I want to plot the 4x4 matrices next to each other in a single plot with matplotlib's imshow function, so it should look like this:

[[ 1.,  1.,  2.,  2.,  3.,  3.,  4.,  4.],
 [ 1.,  1.,  2.,  2.,  3.,  3.,  4.,  4.],
 [ 5.,  5.,  6.,  6.,  7.,  7.,  8.,  8.],
 [ 5.,  5.,  6.,  6.,  7.,  7.,  8.,  8.],
 [ 9.,  9., 10., 10., 11., 11., 12., 12.],
 [ 9.,  9., 10., 10., 11., 11., 12., 12.],
 [13., 13., 14., 14., 15., 15., 16., 16.],
 [13., 13., 14., 14., 15., 15., 16., 16.]]

Is this even possible? I would like to use only numpy functions and avoid for-loops for performance reasons, but if that's not possible another solution would also be great.

标签: pythonnumpymatplotlib

解决方案


这是我要做的:

# other sample:
arr=np.arange(64).reshape(4,4,2,2)

arr.swapaxes(2,1).reshape(arr.shape[0] * arr.shape[2],-1)

输出:

array([[ 0,  1,  4,  5,  8,  9, 12, 13],
       [ 2,  3,  6,  7, 10, 11, 14, 15],
       [16, 17, 20, 21, 24, 25, 28, 29],
       [18, 19, 22, 23, 26, 27, 30, 31],
       [32, 33, 36, 37, 40, 41, 44, 45],
       [34, 35, 38, 39, 42, 43, 46, 47],
       [48, 49, 52, 53, 56, 57, 60, 61],
       [50, 51, 54, 55, 58, 59, 62, 63]])

推荐阅读