我有一个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
的最后一列的正确方法是什么?谢谢!
答案 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)
np.concatenate将起作用
做
y_test = np.array([y_test])
np.concatenate((X_test, y_test), axis = 1)
如果不起作用,请尝试使用.T转置数组,以使轴位于正确的位置。