Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy 3D array arranging and reshaping

Tags:

python

numpy

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

like image 691
motaha Avatar asked Mar 24 '26 09:03

motaha


1 Answers

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.

like image 55
tom10 Avatar answered Mar 26 '26 22:03

tom10



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!