Convert numpy 3d array to 2d array in python

Or convert 2d array to 1d array

Attention: All the below arrays are numpy arrays.

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

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

The rule is:

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

Example — 1:

result is a 2d array with this shape:

Example — 2:

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

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

We need first to transpose A that gives:

  • 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:

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

in one line command it is:

Example —3:

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

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

We need only this:

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

Posting daily about Python, Nuclear Physicist PhD