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

DavidG
  • 24,279
  • 14
  • 89
  • 82
koukou
  • 77
  • 5

3 Answers3

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]])
w-m
  • 10,772
  • 1
  • 42
  • 49
  • @Yuca: There is no distinction between a row and a column vector for a 1d array. See e.g. https://stackoverflow.com/a/42908123/463796 for more on that. – w-m Oct 05 '18 at 15:58
  • 1
    @Yuca you can use the transpose with `np.atleast_2d`: `np.hstack([a, np.atleast_2d(b).T])`. – user3483203 Oct 05 '18 at 16:22
1

Using numpy broadcast with concatenate

np.concatenate([a,b[:,None]],1)
Out[1053]: 
array([[1, 2, 3, 0],
       [5, 6, 7, 1]])
BENY
  • 317,841
  • 20
  • 164
  • 234
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]])
user3483203
  • 50,081
  • 9
  • 65
  • 94
  • Oh, I didn't know about that! And it's implemented essentially as @Wen's answer. Fun! :) – w-m Oct 05 '18 at 16:32
  • Yep, `column_stack` is the only one of the stacking functions (I believe), that converts 1D inputs to 2D columns, so works perfectly here. – user3483203 Oct 05 '18 at 16:35