Mauro
Mauro

Reputation: 1

Convert two-dimensional array of two-dimensional arrays into a two-dimensional array in numpy

I have the following two-dimensional array of two dimensional arrays (i.e., a block matrix):

M = np.array([[[[-26.,  20.],
     [ 20., -20.]],

    [[-42.,  30.],
     [ 30., -32.]]],


   [[[-42.,  30.],
     [ 30., -32.]],

    [[-42.,  30.],
     [ 30., -32.]]]])

and I would like to convert it into a two-dimensional array as follows:

M2 = np.array([[-26, -20, -42, 30], [20, -20, 30, -32], [-42, 30, -42, 30], [30, -32, 30, -32]])

I am looking for an elegant solution without using loops. Can anyone help me? Thank you in advance.

Upvotes: 0

Views: 48

Answers (1)

akuiper
akuiper

Reputation: 214987

You have a 4d array and the order of your output does not match the order of input. You need to transpose the array (rotate the axes) first before reshaping:

row_size = M.shape[-1] * M.shape[0]

M.transpose((1, 2, 0, 3)).reshape(-1, row_size)

[[-26.  20. -42.  30.]
 [ 20. -20.  30. -32.]
 [-42.  30. -42.  30.]
 [ 30. -32.  30. -32.]]

Or equivalently stack the subarray along it's last axis, and then reshape:

row_size = M.shape[-1] * M.shape[0]

np.stack(M, 2).reshape(-1, row_size)

[[-26.  20. -42.  30.]
 [ 20. -20.  30. -32.]
 [-42.  30. -42.  30.]
 [ 30. -32.  30. -32.]]

Upvotes: 0

Related Questions