2

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 example, so I can't sort the array A to obtain B.

I suppose I need more reshapes...

3
  • Can you provide a little more context? Strictly speaking, numpy.sort(A.flatten()) will achieve this result. But I'm guessing this isn't your real data and we can't rely on sorting to get the order that you want. Commented Jun 12, 2017 at 15:39
  • @PaulH I've edit the question. Your answer works for the example, but I can't use sort (I have random numbers) Commented Jun 12, 2017 at 15:46
  • 1
    I figured. Still need a few more details. How general of a solution are you trying to make? For example: are you always going to be dealing with a square array (N x N, where N is even) that is divided into quadrants? Or is it always divided up into any number of 3x3 chunks? Commented Jun 12, 2017 at 15:54

1 Answer 1

5

Split each of those two axes such that the remaining ones are of lengths 2 each with a reshape giving us a 4D array and then swap the middle two axes with np.swapaxes() and finally flatten with np.ravel() -

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.])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.