简体   繁体   English

在 Python 中连接二维 numpy arrays

[英]Concatenating 2 dimensional numpy arrays in Python

I want to concatenate these two arrays我想连接这两个 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尝试使用 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) (stackoverflow 的新手,抱歉,如果我没有很好地格式化这个)

You can use hstack and vector broadcasting for that:您可以为此使用hstack和矢量广播:

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: 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 .请注意,您不能使用concatenate ,因为数组具有不同的形状 hstack stack horizontally the multi-dimentional arrays so it just add a new line at the end here. hstack多维arrays 水平堆叠,所以它只是在此处的末尾添加一个新行。 A broadcast operation ( b[:,None] ) is needed so that the appended vector is a vertical one.需要广播操作( b[:,None] ),以便附加向量是垂直向量。

You can do it like this:你可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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