23

I have a numpy 2D array [[1,2,3]]. I need to append a numpy 1D array,( say [4,5,6]) to it, so that it becomes [[1,2,3], [4,5,6]]

This is easily possible using lists, where you just call append on the 2D list.

But how do you do it in Numpy arrays?

np.concatenate and np.append dont work. they convert the array to 1D for some reason.

Thanks!

1
  • vstack does np.concatenate([np.atleast_2d(m) for m in tup], 0) - in other words - make sure all inputs are 2d and then concatenate. Commented Feb 17, 2016 at 21:20

2 Answers 2

20

You want vstack:

In [45]: a = np.array([[1,2,3]])

In [46]: l = [4,5,6]

In [47]: np.vstack([a,l])
Out[47]: 
array([[1, 2, 3],
       [4, 5, 6]])

You can stack multiple rows on the condition that The arrays must have the same shape along all but the first axis.

In [53]: np.vstack([a,[[4,5,6], [7,8,9]]])
Out[53]: 
array([[1, 2, 3],
       [4, 5, 6],
       [4, 5, 6],
       [7, 8, 9]])
Sign up to request clarification or add additional context in comments.

2 Comments

it doesn't work similarly with hstack though... col_vector_to_append = np.column_stack([4, 5, 6]).T is needed
@Mehdi surely vstack is the transposed version of hstack right?
1

Try this:

np.concatenate(([a],[b]),axis=0)

when

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

then result should be:

array([[1, 2, 3], [4, 5, 6]])

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.