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
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]])
Using numpy
broadcast with concatenate
np.concatenate([a,b[:,None]],1)
Out[1053]:
array([[1, 2, 3, 0],
[5, 6, 7, 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]])