numpy:concat /在原始矩阵中追加一个附加列

时间:2017-08-09 20:24:41

标签: python-3.x numpy matrix

我有一个numpy矩阵X_test和一个y_test系列,它们的尺寸为:

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

(5, 9)
(5,)

然后我尝试将y_test添加为X_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 个答案:

答案 0 :(得分: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。理解和更改数组的维度对于高效numpy工作至关重要。

答案 1 :(得分:1)

如果你将y_test更改为(5,1)而不是(5,),那么

np.concatenate将起作用

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

如果不起作用,请尝试使用.T转置数组,以使轴位于正确的位置。