motaha
motaha

Reputation: 403

Numpy 3D array arranging and reshaping

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

Upvotes: 3

Views: 5568

Answers (2)

BENSALEM Mouhssen
BENSALEM Mouhssen

Reputation: 71

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]]])

Upvotes: 2

tom10
tom10

Reputation: 69192

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.

Upvotes: 6

Related Questions