0

I have a 4-D array which I need to convert to 2-D, do some operations, and then convert back to 4-D. It is important that the order of the elements are preserved for the operation. From this post I got out how to do this reshape operation using np.swapaxes(1, 2).

But now I am confused how to re-shape it back to the original 4D matrix that started of with.

How do I do this with standard numpy methods.

Ananda
  • 2,925
  • 5
  • 22
  • 45

1 Answers1

1

4 to 2 and back:

In [348]: arr4 = np.arange(2*3*4*5).reshape(2,3,4,5)
In [349]: arr2 = arr4.transpose(0,2,1,3).reshape(8,15)
In [350]: arr2
Out[350]: 
array([[  0,   1,   2,   3,   4,  20,  21,  22,  23,  24,  40,  41,  42,
         43,  44],
       [  5,   6,   7,   8,   9,  25,  26,  27,  28,  29,  45,  46,  47,
         48,  49],
       [ 10,  11,  12,  13,  14,  30,  31,  32,  33,  34,  50,  51,  52,
         53,  54],
       [ 15,  16,  17,  18,  19,  35,  36,  37,  38,  39,  55,  56,  57,
         58,  59],
       [ 60,  61,  62,  63,  64,  80,  81,  82,  83,  84, 100, 101, 102,
        103, 104],
       [ 65,  66,  67,  68,  69,  85,  86,  87,  88,  89, 105, 106, 107,
        108, 109],
       [ 70,  71,  72,  73,  74,  90,  91,  92,  93,  94, 110, 111, 112,
        113, 114],
       [ 75,  76,  77,  78,  79,  95,  96,  97,  98,  99, 115, 116, 117,
        118, 119]])

In [351]: arrN = arr2.reshape(2,4,3,5).transpose(0,2,1,3)
In [352]: np.allclose(arr4,arrN)
Out[352]: True

I'm using transpose with parameter, but swapaxes would work just as well. For testing it's convenient to keep dimensions distinct. That way most mistakes will result in errors or obvious mismatches. The original 4x5 inner blocks are still evident in the 2d array.

hpaulj
  • 221,503
  • 14
  • 230
  • 353