Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

Let's say I have a 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.]]

 I would like to use only the NumPy functions and avoid for-loops for performance reasons, but if that's not possible then how to solve it.

1 Answer

0 votes
by (36.8k points)

What you can do is:

# other sample:

arr=np.arange(64).reshape(4,4,2,2)

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

Output:

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]])

Want to be a Data Science expert? Come and join this Data Science Courses

 

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...