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)

3
  • You can use extend(): possible duplicate of this question Commented Apr 15, 2021 at 13:58
  • Does this answer your question? Concatenate a NumPy array to another NumPy array Commented Apr 15, 2021 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? Commented Apr 15, 2021 at 14:07

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can do it like this:

np.append(a,b.reshape(-1,1),axis=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.