1

I have two numpy arrays of the form np.array([1,2,3])) I want to concatenate them so I get:

[[1,2,3],[4,5,6]] 

and it also has to work when there is a numpy array of the form [[1,2,3],[4,5,6]] and another one [7,8,9] and I want to get:

[[1,2,3],[4,5,6],[7,8,9]]

I tried np.concatenate but I couldn't get it to work

3
  • What error did you get? Describe your array dimensions, input and desired. Commented Jan 28, 2021 at 20:31
  • I kept getting [1,2,3,4,5,6] instead. The array dimensions change, the only constant is the length of the inside arrays (in the examples 3) Commented Jan 28, 2021 at 20:37
  • You forgot to read the concatenate docs. :) Commented Jan 28, 2021 at 21:03

1 Answer 1

2

You can use vstack for this:

import numpy as np

a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.array([7,8,9])

d = np.vstack((a,b))

e = np.vstack((d, c))

print(d)
print(e)

Gives:

[[1 2 3]
 [4 5 6]]    

[[1 2 3]
 [4 5 6]
 [7 8 9]]
Sign up to request clarification or add additional context in comments.

2 Comments

Though to use concatenate the 1d inputs have to first have a new leading axis added.
@hpaulj: Thanks for the comment, and yes, it wasn't setting the axis (as I mistakenly said) but adding a leading axis. I just removed the concatenate comment since it didn't help the answer and doing concatenate seems a distraction in this case.

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.