0

Given a 4 2d array as below

import numpy as np
    
t1=np.array([[0,0,1],[0,0,1],[1,1,0]])
t2=np.array([[0,1,0],[1,0,1],[0,1,0]])
t3=np.array([[0,0,1],[0,0,0],[1,0,0]])
t4=np.array([[0,1,1],[1,0,1],[1,1,0]])

May I know how to combine and reshape it to get the output as below

[[[0. 0. 0. 0.]
      [0. 1. 0. 1.]
      [1. 0. 1. 1.]]
     [[0. 1. 0. 1.]
      [0. 0. 0. 0.]
      [1. 1. 0. 1.]]
     [[1. 0. 1. 1.]
      [1. 1. 0. 1.]
      [0. 0. 0. 0.]]]

3 Answers 3

1
In [66]: t1=np.array([[0,0,1],[0,0,1],[1,1,0]])
    ...: t2=np.array([[0,1,0],[1,0,1],[0,1,0]])
    ...: t3=np.array([[0,0,1],[0,0,0],[1,0,0]])
    ...: t4=np.array([[0,1,1],[1,0,1],[1,1,0]])
In [67]: t1.shape
Out[67]: (3, 3)
In [68]: np.stack((t1,t2,t3,t4),axis=2)
Out[68]: 
array([[[0, 0, 0, 0],
        [0, 1, 0, 1],
        [1, 0, 1, 1]],

       [[0, 1, 0, 1],
        [0, 0, 0, 0],
        [1, 1, 0, 1]],

       [[1, 0, 1, 1],
        [1, 1, 0, 1],
        [0, 0, 0, 0]]])

Transpose of the array (also np.stack((), axis=0)) produces the same thing, but that is only because each of the (3,3) arrays are symmetric.

In [70]: np.array((t1,t2,t3,t4))
Out[70]: 
array([[[0, 0, 1],
        [0, 0, 1],
        [1, 1, 0]],

       [[0, 1, 0],
        [1, 0, 1],
        [0, 1, 0]],

       [[0, 0, 1],
        [0, 0, 0],
        [1, 0, 0]],

       [[0, 1, 1],
        [1, 0, 1],
        [1, 1, 0]]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the suggestion, safe to say directly transpose will fail if we have asymmetrical last 2 dimension? I have not check this with large dimension thou
1
print(np.array([t1,t2,t3,t4]).T)

Comments

1
In [1]: import numpy as np

In [2]: t1=np.array([[0,0,1],[0,0,1],[1,1,0]])
   ...: t2=np.array([[0,1,0],[1,0,1],[0,1,0]])
   ...: t3=np.array([[0,0,1],[0,0,0],[1,0,0]])
   ...: t4=np.array([[0,1,1],[1,0,1],[1,1,0]])

In [3]: np.array((t1, t2, t3, t4)).T
Out[3]:
array([[[0, 0, 0, 0],
        [0, 1, 0, 1],
        [1, 0, 1, 1]],

       [[0, 1, 0, 1],
        [0, 0, 0, 0],
        [1, 1, 0, 1]],

       [[1, 0, 1, 1],
        [1, 1, 0, 1],
        [0, 0, 0, 0]]])

The .T is equivalent to the transpose function.

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.