2

How can I do if:

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

b = np.array([0,1])

I search to concatenate a and b so as the result would be:

np.array([1,2,3,0],[5,6,7,1])

Thanks a lot

3 Answers 3

3

The problem is to concatenate a horizontally with b as a column vector.

<concat>( |1 2 3|, |0| )
          |5 6 7|  |1|

The concatentation can be done using np.hstack, and b can be converted into a column vector by adding a new axis:

>>> np.hstack([a, b[:, np.newaxis]])
array([[1, 2, 3, 0],
       [5, 6, 7, 1]])
Sign up to request clarification or add additional context in comments.

2 Comments

@Yuca: There is no distinction between a row and a column vector for a 1d array. See e.g. stackoverflow.com/a/42908123/463796 for more on that.
@Yuca you can use the transpose with np.atleast_2d: np.hstack([a, np.atleast_2d(b).T]).
1

The more numpythonic way to do this is to avoid broadcasting, and use the function designed for this: numpy.column_stack:

np.column_stack([a, b])

array([[1, 2, 3, 0],
       [5, 6, 7, 1]])

2 Comments

Oh, I didn't know about that! And it's implemented essentially as @Wen's answer. Fun! :)
Yep, column_stack is the only one of the stacking functions (I believe), that converts 1D inputs to 2D columns, so works perfectly here.
1

Using numpy broadcast with concatenate

np.concatenate([a,b[:,None]],1)
Out[1053]: 
array([[1, 2, 3, 0],
       [5, 6, 7, 1]])

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.