0

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 ?

3
  • Does this answer your question? Append 2D array to 3D array, extending third dimension Commented May 21, 2022 at 13:42
  • 1
    @blunova The accepted answer on that Q (use dstack) doesn't work in this case, where the 'missing' axis is the first one. Personally I think adding an axis and using some form of stack is a more general solution. Commented May 21, 2022 at 13:58
  • @kwinkunks I'm sorry, you are right! Thanks for noticing! Commented May 21, 2022 at 14:13

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.