Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Stacking 2D arrays into a 3D array

I have a very simple question but I just can’t figure it out. I would like to stack a bunch of 2D numpy arrays into a 3D array one by one along the third dimension (depth).

I know that I can use np.stack() like this:

d1 = np.arange(9).reshape(3,3)
d2 = np.arange(9,18).reshape(3,3)

foo = np.stack((d1,d2))

and I get

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

print(foo.shape)
>>> (2, 3, 3)
print(foo)
>>> [[[ 0  1  2]
      [ 3  4  5]
      [ 6  7  8]]

     [[ 9 10 11]
      [12 13 14]
      [15 16 17]]]

Which is pretty much what I want so far. Though, I am a bit confused here that the depth dimension is indexed as the first one here.
However, I would like to add new 3×3 array along the first dimension now(?) (this confuses me), like this.

d3 = np.arange(18,27).reshape(3,3)
foo = np.stack((foo,d3))

This does not work. I understand that it has a problem with dimensions of the arrays now, but no vstack, hstack, dstack work here. All I want at this point is pretty much this.

print(foo)
>>> [[[ 0  1  2]
      [ 3  4  5]
      [ 6  7  8]]

     [[ 9 10 11]
      [12 13 14]
      [15 16 17]]

     [[18 19 20]
      [21 22 23]
      [24 25 26]]]

and then just be able to add more arrays like this.

I looked at some questions on this topic, of course, but I still have problem understanding 3D arrays (especially np.dstack()) and don’t know how to solve my problem.

>Solution :

Why don’t you add directly d1, d2, d3 in a single stack (np.stack((d1, d2, d3)))? This is generally bad practice to repeatedly concatenate arrays.

In any case, you can use:

np.stack((*foo, d3))

or:

np.vstack((foo, d3[None]))

output:

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

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading