簡體   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