Home > Blockchain >  Append 2d array to 3d array
Append 2d array to 3d array

Time:05-22

I have an array of shape (3, 250, 15).

I want to append to it a 2d array of shape (250,15) so that I have a final shape of (4,250,15). I tried with dstack and np.stack but it does not work.

Can someone give me a suggestion ?

CodePudding user response:

You need to add a dimension (in other words, an axis) to the 2-D array, for example:

import numpy as np

a = np.ones((3, 250, 15))
b = np.ones((250, 15))

c = np.vstack([a, b[None, :, :]])

Now c has shape (4, 250, 15).

If you're not into the None axis trick, you could achieve something similar with np.newaxis or np.reshape.

CodePudding user response:

You can't append a 2D array to a 3D array directly, so you should first expand the axes of the smaller array to become 3D and then append normally. np.expand_dims(b, axis=0) will insert the missing first-axis to array b. Now append the two 3D arrays, np.append(a, b, axis=0).

import numpy as np

a = np.ones((3, 250, 15))
b = np.ones((   250, 15))

b = np.expand_dims(b, axis=0)
c = np.append(a, b, axis=0) 

which works as expected.

print(c.shape)
 (4, 250, 15)
  • Related