3

I want to concatenate these two arrays

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

such that

a = [[1,2,3,9],[3,4,5,10],[6,7,8,11]]

Tried using concatenate

for i in range(len(a)):
  a[i] = np.concatenate(a[i],[b[i]])

Got an error:

TypeError: 'list' object cannot be interpreted as an integer

Tried using append

for i in range(len(a)):
  a[i] = np.append(a[i],b[i])

Got another error:

ValueError: could not broadcast input array from shape (4,) into shape (3,)

(New to stackoverflow, sorry if I didn't format this well)

N_ E
  • 33
  • 3
  • You can use [**`extend()`**](https://www.geeksforgeeks.org/append-extend-python/): possible duplicate of [**this question**](https://stackoverflow.com/questions/8177079/take-the-content-of-a-list-and-append-it-to-another-list) – D_00 Apr 15 '21 at 13:58
  • Does this answer your question? [Concatenate a NumPy array to another NumPy array](https://stackoverflow.com/questions/9775297/concatenate-a-numpy-array-to-another-numpy-array) – alex Apr 15 '21 at 14:05
  • seems like extend() only works for list. I can convert them to lists, extend them, then convert it back to a numpy array. But there gotta be a better way to do it right? – N_ E Apr 15 '21 at 14:07

2 Answers2

1

You can use hstack and vector broadcasting for that:

a = np.array([[1,2,3],[3,4,5],[6,7,8]])  
b = np.array([9,10,11])
res = np.hstack((a, b[:,None]))
print(res)

Output:

[[ 1  2  3  9]
 [ 3  4  5 10]
 [ 6  7  8 11]]

Note that you cannot use concatenate because the array have different shapes. hstack stack horizontally the multi-dimentional arrays so it just add a new line at the end here. A broadcast operation (b[:,None]) is needed so that the appended vector is a vertical one.

Jérôme Richard
  • 41,678
  • 6
  • 29
  • 59
1

You can do it like this:

np.append(a,b.reshape(-1,1),axis=1)
XtianP
  • 389
  • 2
  • 5