【问题标题】:numpy: concat/append one additional column to the original matrixnumpy:连接/附加一列到原始矩阵
【发布时间】:2017-08-09 20:24:41
【问题描述】:

我有一个 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 的最后一列的正确方法应该是什么?谢谢!

【问题讨论】:

    标签: python-3.x numpy matrix


    【解决方案1】:

    正确的做法是给y_test一个新的维度。你知道reshapenp.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 高效工作的核心。

    【讨论】:

      【解决方案2】:

      如果您将 y_test 更改为 (5,1) 而不是 (5,),则 np.concatenate 将起作用

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

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

      【讨论】:

      • 你的y_test修改为y_test[None,:],在开头添加一个新维度,变成(1,5)
      猜你喜欢
      • 1970-01-01
      • 2016-02-29
      • 2015-10-06
      • 1970-01-01
      • 2021-10-25
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多