Convert numpy 3d array to 2d array in python

Or convert 2d array to 1d array

Panjeh
2 min readJun 23, 2020

Attention: All the below arrays are numpy arrays.

Imagine we have a 3d array (A) with this shape:

A.shape = (a,b,c)

Now we want to convert it to a 2d array (B) with this shape:

B.shape = (a*b, c)

The rule is:

B = A.reshape(-1,c)

When we use -1 in reshape() method, it means we multiply the first two dimensions.

Example — 1:

D = A.reshape(a,-1)

result is a 2d array with this shape:

D.shape = (a, b*c)

Example — 2:

If we want to have a 2d array (E) with the shape:

E.shape = (c, a*b)

From the 3d array (A), where its shape is

A.shape = (a,b,c)

We need first to transpose A that gives:

F = A.transpose(2,0,1)
  • where 2 is the index number of c in shape (a, b, c)
  • where 0 is the index number of a in shape (a, b, c)
  • where 1 is the index number of b in shape (a, b, c)

Which gives a new 3d array (F) with this shape:

F.shape = (c, a, b)

Now we can reshape F to make a 2d array (E) that is:

E = F.reshape(c,-1)

in one line command it is:

E = A.transpose(2,0,1).reshape(c,-1)

Example —3:

Now converting a 2d array to a 1d array:

Assume we have a 2d array (G) with the shape:

G.shape = (a, b)

We need only this:

H = G.reshape(-1)

Now we will have a 1d array (H) with the shape:

H.shape = (a*b)

--

--