Reshape 3D numpy matrix to 2D numpy matrix, maintaining row position

Viewed 49

As a simplified example, I have a 3D numpy matrix that looks like this:

a = np.array([[[1,2],
               [4,np.nan],
               [7,8]],

              [[7,6],
               [4,3],
               [1,0]],

              [[0,1],
               [3,np.nan]
               [6,7]],

              [[8,7],
               [5,4],
               [2,1]]])
>>> a.shape
(4,3,2)

I'd like to reshape this 3D matrix (a) to a 2D matrix (b) while maintaining row position. This is the goal:

b = np.array([[1,2,7,6,0,1,8,7],
              [4,np.nan,4,3,3,np.nan,5,4],
              [7,8,1,0,6,7,2,1]])
>>> b.shape
(3,8)

I think I should be able to achieve this with some combination of .reshape() and .transpose()? But I'm pretty new to this matrix manipulation stuff and it's all a bit mind-boggling. Nothing I've tried so far quite gets me there...

1 Answers

You can first swap the first 2 axes with transpose (so that the shape will be (3, 4, 2)) and then reshape:

>>> a.transpose(1, 0, 2).reshape(3, 8)

array([[ 1.,  2.,  7.,  6.,  0.,  1.,  8.,  7.],
       [ 4., nan,  4.,  3.,  3., nan,  5.,  4.],
       [ 7.,  8.,  1.,  0.,  6.,  7.,  2.,  1.]])
Related