P-Gn
P-Gn

Reputation: 24661

Python/Numpy: rearrange N4xN3xN2xN1 4D array into an (N4.N2)x(N3.N1) 2D array

For example, if:

a = numpy.array([[[[1,2],[3,4]],[[5,6],[7,8]]],[[[11,12],[13,14]],[[15,16],[17,18]]]])

then I would like to eventually obtain:

1  2  5  6
3  4  7  8
11 12 15 16
13 14 17 18

Simple reshaping won't work unfortunately.

Upvotes: 2

Views: 81

Answers (1)

Alex Riley
Alex Riley

Reputation: 177088

You need to swap the second and third axes first, and then reshape:

>>> a.swapaxes(1, 2).reshape(4, 4)
array([[ 1,  2,  5,  6],
       [ 3,  4,  7,  8],
       [11, 12, 15, 16],
       [13, 14, 17, 18]])

Upvotes: 4

Related Questions