简体   繁体   中英

Concatenating 2 dimensional numpy arrays in Python

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)

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.

You can do it like this:

np.append(a,b.reshape(-1,1),axis=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM