Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reshape numpy 3D array to 2D

I have a very big array with the shape = (32, 3, 1e6) I need to reshape it to this shape = (3, 32e6)

On a snippet, how to go from this::

>>> m3_3_5
array([[[8, 4, 1, 0, 0],
        [6, 8, 5, 5, 2],
        [1, 1, 1, 1, 1]],

       [[8, 7, 1, 0, 3],
        [2, 8, 5, 5, 2],
        [1, 1, 1, 1, 1]],

       [[2, 4, 0, 2, 3],
        [2, 5, 5, 3, 2],
        [1, 1, 1, 1, 1]]])

to this::

>>> res3_15
array([[8, 4, 1, 0, 0, 8, 7, 1, 0, 3, 2, 4, 0, 2, 3],
       [6, 8, 5, 5, 2, 2, 8, 5, 5, 2, 2, 5, 5, 3, 2],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])

I did try various combinations with reshape with no success::

>>> dd.T.reshape(3, 15)
array([[8, 8, 2, 6, 2, 2, 1, 1, 1, 4, 7, 4, 8, 8, 5],
       [1, 1, 1, 1, 1, 0, 5, 5, 5, 1, 1, 1, 0, 0, 2],
       [5, 5, 3, 1, 1, 1, 0, 3, 3, 2, 2, 2, 1, 1, 1]])

>>> dd.reshape(15, 3).T.reshape(3, 15)
array([[8, 0, 8, 2, 1, 8, 0, 8, 2, 1, 2, 2, 5, 2, 1],
       [4, 0, 5, 1, 1, 7, 3, 5, 1, 1, 4, 3, 5, 1, 1],
       [1, 6, 5, 1, 1, 1, 2, 5, 1, 1, 0, 2, 3, 1, 1]])
like image 493
user3313834 Avatar asked Feb 18 '16 00:02

user3313834


People also ask

How do you convert a 3D array to a 2D array?

reshape() function to convert a 3D array with dimensions (4, 2, 2) to a 2D array with dimensions (4, 4) in Python. In the above code, we first initialize a 3D array arr using numpy. array() function and then convert it into a 2D array newarr with numpy. reshape() function.


1 Answers

a.transpose([1,0,2]).reshape(3,15) will do what you want. (I am basically following comments by @hpaulj).

In [14]: a = np.array([[[8, 4, 1, 0, 0],
        [6, 8, 5, 5, 2],
        [1, 1, 1, 1, 1]],

       [[8, 7, 1, 0, 3],
        [2, 8, 5, 5, 2],
        [1, 1, 1, 1, 1]],

       [[2, 4, 0, 2, 3],
        [2, 5, 5, 3, 2],
        [1, 1, 1, 1, 1]]])

In [15]: a.transpose([1,0,2]).reshape(3,15)
Out[15]: 
array([[8, 4, 1, 0, 0, 8, 7, 1, 0, 3, 2, 4, 0, 2, 3],
       [6, 8, 5, 5, 2, 2, 8, 5, 5, 2, 2, 5, 5, 3, 2],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
like image 174
Akavall Avatar answered Sep 25 '22 05:09

Akavall