繁体   English   中英

将列向量连接到矩阵的末尾

[英]concatenate a column vector to the end of a matrix

我试图在矩阵的末尾添加一个列向量,如下所示:

import numpy as np
datas=[[1,2],[3,4]]
temp=[1,2]
datas=np.array(datas)
temp=np.transpose(np.array(temp))

np.append(datas,temp,axis=1)

但是我收到尺寸不匹配错误?

那我该怎么做呢?

您需要向 temp 添加一维,以便两个数组具有相同的维度

import numpy as np
datas=[[1,2],[3,4]]
temp=[1,2]
datas=np.array(datas)
temp=np.array(temp)[:, np.newaxis] ## this adds new dimension 

np.append(datas,temp,axis=1)

您也可以使用如下所示的连接 function 来做到这一点。 如果您连接两个以上的 arrays,它的性能会更好。 在这里,您在循环中创建 python list ls 然后将它们连接起来

ls = [datas,temp]
np.concatenate(ls, axis=1)

建议您只使用 np.expand_dims() 然后 np.hstack()

datas=[[1,2],[3,4]]
temp=[1,2]

#Expand the dims of temp
temp = np.expand_dims(temp,1) 

#Stack horizontally
np.hstack((datas, temp))
array([[1, 2, 1],
       [3, 4, 2]])

暂无
暂无

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

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