Home > Software design >  Stacking 2D arrays into a 3D array
Stacking 2D arrays into a 3D array

Time:06-02

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

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 3x3 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.

CodePudding user response:

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]]])

CodePudding user response:

You can create an array as you like then reshape it with (-1,...) for dimension as like:

>>> np.arange(36).reshape(-1,3,3)
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]],

       [[27, 28, 29],
        [30, 31, 32],
        [33, 34, 35]]])

CodePudding user response:

You are looking for np.vstack:

np.vstack((d1,d2,d3)).reshape(3,3,3)

or iteratively

foo = np.vstack((d1, d2))
foo = np.vstack((foo, d3))
  • Related