2

I want to reshape a into b, how to quickly do it?

Basically, when reshaping the array, how to always use the first item in each group, then the second item, then the third one?

Input:

import numpy as np

# 3 repeats, each has 2 variables, each has 4 times
a=np.array([[['r1_v1_t1','r1_v1_t2','r1_v1_t3','r1_v1_t4'],
            ['r1_v2_t1','r1_v2_t2','r1_v2_t3','r1_v2_t4']],

[['r2_v1_t1','r2_v1_t2','r2_v1_t3','r2_v1_t4'],
            ['r2_v2_t1','r2_v2_t2','r2_v2_t3','r2_v2_t4']],

[['r3_v1_t1','r3_v1_t2','r3_v1_t3','r3_v1_t4'],
            ['r3_v2_t1','r3_v2_t2','r3_v2_t3','r3_v2_t4']]
            ])

# 4 times, each has 3 repeats, each has 2 variables
b=np.array([[['r1_v1_t1','r1_v2_t1'],['r2_v1_t1','r2_v2_t1'],['r3_v1_t1','r3_v2_t1']],
[['r1_v1_t2','r1_v2_t2'],['r2_v1_t2','r2_v2_t2'],['r3_v1_t2','r3_v2_t2']],
[['r1_v1_t3','r1_v2_t3'],['r2_v1_t3','r2_v2_t3'],['r3_v1_t3','r3_v2_t3']],
[['r1_v1_t4','r1_v2_t4'],['r2_v1_t4','r2_v2_t4'],['r3_v1_t4','r3_v2_t4']]])

# 4 times, each has 2 variables, each has 3 repeats
#print(a.T)

#print(np.reshape(a,(4,3,2), order='F')) not work
#print(np.reshape(a,(4,3,2))) not work
3
  • 1
    Could you not just do a.reshape(b.shape, order='F')? Commented Mar 23, 2018 at 16:09
  • 2
    b=a.T Just transpose it. Commented Mar 23, 2018 at 16:11
  • thank you! The transpose works! Sorry, I was actually trying to solve a more complex problem, so I re-edited the question now. Commented Mar 23, 2018 at 17:14

1 Answer 1

1

You can swap the array's axes so the shape of a matches the shape of b. Numpy's swapaxes can achieve this:

new_a = np.swapaxes( np.swapaxes(a,0,2) ,1,2)

You can test that this new_a is equivalent to b:

print (new_a == b).all()  # True

Here's a working gist.

Sign up to request clarification or add additional context in comments.

1 Comment

fantastic! so powerful!

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.