将一个可混合数组追加(hstack)到矩阵会返回错误

时间:2016-10-07 22:08:29

标签: python append

我正在尝试np.hstack数组到矩阵。该数组具有.shape (a,),矩阵具有.shape (a,b),其中ab整数。我收到尺寸不匹配的错误(all the input arrays must have same number of dimensions)。我该怎么做hstack这些适合的对象?

3 个答案:

答案 0 :(得分:1)

我认为问题在于你所谓的数组是1维的,而矩阵是2维的。

我们假设他们被称为MNM.shape提供(a,)(正如您所说的那样#34;数组")N.shape给出(a,b)(正如您所说的那样"矩阵&# 34)。如果您执行M = M.reshape(a, 1),则会获得与Nnp.hstack((M, N))相同行数的二维数组。

P.S:你提到的所有实体都是数组,也许你的意思是第一个实体的矢量或一维数组。

编辑 - 例如:

>>> import numpy as np
>>> a=  np.array([1,2,3])
>>> a.shape
(3,)

>>> b = np.array([[1], [2], [3]])
>>> b.shape
(3,1)

>>> c = np.hstack((a.reshape(3, 1), b))
>>> c
array([[1, 1],
       [2, 2],
       [3, 3]])
>>> c.shape
(3,2)

答案 1 :(得分:1)

使用Nonenp.newaxis额外轴添加到第一个数组:

>>> import numpy as np
>>> a=  np.array([1,2,3])
>>> a.shape
(3,)
>>> b = np.array([[1], [2], [3]])
>>> b.shape
(3, 1)
>>> np.hstack((a[:, None], b))
array([[1, 1],
       [2, 2],
       [3, 3]])

答案 2 :(得分:0)

另一种选择是

np.transpose(np.asmatrix(a))

在追加之前。