DiegoDZ DiegoDZ -3 years ago 70
Python Question

Reshape arrays with python

I have the array

A = array([[ 1., 2., 3., 10., 11., 12.],
[ 4., 5., 6., 13., 14., 15.],
[ 7., 8., 9., 16., 17., 18.],
[ 19., 20., 21., 28., 29., 30.],
[ 22., 23., 24., 31., 32., 33.],
[ 25., 26., 27., 34., 35., 36.]])


I would like to reshape it in order to obtain

B = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36]


I have tried

>>> B = A.reshape(1,36)
array([[ 1., 2., 3., 10., 11., 12., 4., 5., 6., 13., 14.,
15., 7., 8., 9., 16., 17., 18., 19., 20., 21., 28.,
29., 30., 22., 23., 24., 31., 32., 33., 25., 26., 27.,
34., 35., 36.]])


But, obviously, I didn't reach the result. My real data differs from the exmaple, so I can't sort the array A to obtain B.

I suppose I need more reshapes...

Thanks!

Answer Source

Splt each of those two axes such that the remaining ones are of lengths 2 giving a 4D array and then swap the middle two axes and finally flatten -

A.reshape(2,3,2,3).swapaxes(1,2).ravel()

Generically put -

m,n = A.shape
A.reshape(2,m//2,2,n//2).swapaxes(1,2).ravel()

Sample run -

In [15]: A
Out[15]: 
array([[  1.,   2.,   3.,  10.,  11.,  12.],
       [  4.,   5.,   6.,  13.,  14.,  15.],
       [  7.,   8.,   9.,  16.,  17.,  18.],
       [ 19.,  20.,  21.,  28.,  29.,  30.],
       [ 22.,  23.,  24.,  31.,  32.,  33.],
       [ 25.,  26.,  27.,  34.,  35.,  36.]])

In [16]: A.reshape(2,3,2,3).swapaxes(1,2).ravel()
Out[16]: 
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,
        12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,  22.,
        23.,  24.,  25.,  26.,  27.,  28.,  29.,  30.,  31.,  32.,  33.,
        34.,  35.,  36.])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download