3

I have a 3D numpy array that I need to reshape and arrange. For example, I have x=np.array([np.array([np.array([1,0,1]),np.array([1,1,1]),np.array([0,1,0]),np.array([1,1,0])]),np.array([np.array([0,0,1]),np.array([0,0,0]),np.array([0,1,1]),np.array([1,0,0])]),np.array([np.array([1,0,0]),np.array([1,0,1]),np.array([1,1,1]),np.array([0,0,0])])])

Which is a shape of (3,4,3), when printing it I get:

array([[[1, 0, 1],
        [1, 1, 1],
        [0, 1, 0],
        [1, 1, 0]],

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

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

Now I need to reshape this array to a (4,3,3) by selecting the same index in each subarray and putting them together to end up with something like this:

array([[[1,0,1],[0,0,1],[1,0,0]],
[[1,1,1],[0,0,0],[1,0,1]],
[[0,1,0],[0,1,1],[1,1,1]],
[[1,1,0],[1,0,0],[0,0,0]]]

I tried reshape, all kinds of stacking and nothing worked (arranged the array like I need). I know I can do it manually but for large arrays manually isn't a choice.

Any help will be much appreciated. Thanks

1
  • You can simplify the array creation to: x= np.array([[[1,0,1], [1,1,1],...,1,1], [0,0,0]]]) Commented Jun 28, 2016 at 4:01

2 Answers 2

6

swapaxes will do what you want. That is, if your input array is x and your desired output is y, then

np.all(y==np.swapaxes(x, 1, 0))

should give True.

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

2 Comments

Also, possibly rollaxis. In this case the two will probably be equivalent, but for higher-dimensioned arrays, rollaxis is often the one you want since it preserves the order of the other axes better.
Not sure why this isn't included under "See also" in the numpy documentation for reshape().
2

For higher dimensional arrays, transpose will accept a tuple of axis numbers to permute the axes:

import numpy as np
foo = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]])
foo.transpose(1, 0, 2)

result:

array([[[ 1,  2],
        [ 5,  6],
        [ 9, 10]],

       [[ 3,  4],
        [ 7,  8],
        [11, 12]]])

1 Comment

Sometimes a 5 year old answer with no upvotes can save you tons of time. I'm happy I found this, thank you!

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.