2017-08-09 123 views
0

我有一個numpy的矩陣X_test等一系列y_test,其尺寸爲:numpy的:CONCAT /一個附加列追加到原始矩陣

print(X_test.shape) 
print(y_test.shape) 

(5, 9) 
(5,) 

然後我試圖添加y_testX_test像最後一列如下:

np.concatenate((X_test, y_test), axis = 1) 

,但得到以下錯誤:

--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-53-2edea4d89805> in <module>() 
    24 
---> 25 print(np.concatenate((X_test, y_test), axis = 1)) 

ValueError: all the input arrays must have same number of dimensions 

我也試過:

np.append((X_test, y_test), 1) 

,但也得到了錯誤:

--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-54-f3d5e5ec7978> in <module>() 

---> 26 print(np.append((X_test, y_test), 1)) 

/usr/local/lib/python3.4/dist-packages/numpy/lib/function_base.py in append(arr, values, axis) 
    5139 
    5140  """ 
-> 5141  arr = asanyarray(arr) 
    5142  if axis is None: 
    5143   if arr.ndim != 1: 

/usr/local/lib/python3.4/dist-packages/numpy/core/numeric.py in asanyarray(a, dtype, order) 
    581 
    582  """ 
--> 583  return array(a, dtype, copy=False, order=order, subok=True) 
    584 
    585 

ValueError: could not broadcast input array from shape (5,9) into shape (5) 

我錯過了什麼嗎?添加y_test作爲矩陣X_test的最後一列應該是什麼樣的正確方法?謝謝!

回答

2

正確的方法是給y_test一個新的維度。你知道reshape還是np.newaxis

In [280]: X = np.ones((5,9)) 
In [281]: y = np.ones((5,)) 
In [282]: np.concatenate((X, y), axis=1) 
... 
ValueError: all the input arrays must have same number of dimensions 
In [283]: y.reshape(5,1) 
Out[283]: 
array([[ 1.], 
     [ 1.], 
     [ 1.], 
     [ 1.], 
     [ 1.]]) 

In [285]: np.concatenate((X,y.reshape(5,1)),1).shape 
Out[285]: (5, 10) 
In [287]: np.concatenate((X,y[:,None]),1).shape 
Out[287]: (5, 10) 

np.column_stack做同樣的調整,但它的好,知道如何與concatenate直接工作。理解和改變陣列的尺寸是生產效率的核心。如果你改變你的y_test到(5,1)

1

np.concatenate會工作,而不是(5)

y_test = np.array([y_test]) 
np.concatenate((X_test, y_test), axis = 1) 

如果不工作,然後嘗試用你的轉置數組。 T將軸移動到正確的位置。

+0

您的y_test修改爲'y_test [None,:]',在開始時添加一個新維度,使其成爲'(1,5)'。 – hpaulj