1

I have the array

import numpy as np
a = np.array([[[11,12,13], [14,15,16]],
              [[21,22,23], [24,25,26]],
              [[31,32,33], [34,35,36]]])

# array([[[11, 12, 13],
#         [14, 15, 16]],

#        [[21, 22, 23],
#         [24, 25, 26]],

#        [[31, 32, 33],
#         [34, 35, 36]]])

#a.shape
#(3, 2, 3)

I need to reshape it to a 2D array with three columns:

step1 = a.transpose(1, 2, 0).reshape(-1, 3)
# array([[11, 21, 31],
#        [12, 22, 32],
#        [13, 23, 33],
#        [14, 24, 34],
#        [15, 25, 35],
#        [16, 26, 36]])

I then need to reshape it back to the original shape, but I cant figure out how?

1
  • 1
    step1.reshape(2, 3, 3).transpose(2, 0, 1)? Commented Jun 30 at 19:59

1 Answer 1

3

You probably could try

step1 = a.reshape(3,-1).T
step2 = step1.T.reshape(a.shape)

print(f'step1 :\n {step1}\n')
print(f'step2 :\n {step2}\n')

and you will see

step1 :
 [[11 21 31]
 [12 22 32]
 [13 23 33]
 [14 24 34]
 [15 25 35]
 [16 26 36]]

step2 :
 [[[11 12 13]
  [14 15 16]]

 [[21 22 23]
  [24 25 26]]

 [[31 32 33]
  [34 35 36]]]
Sign up to request clarification or add additional context in comments.

2 Comments

Is the explicit flatten needed? I think the reshape effectively does that before applying the new shape.
@hpaulj aha, you are right, thanks for helping to improve the code :)

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.