我正在尝试np.hstack
数组到矩阵。该数组具有.shape
(a,)
,矩阵具有.shape
(a,b)
,其中a
和b
整数。我收到尺寸不匹配的错误(all the input arrays must have same number of dimensions
)。我该怎么做hstack
这些适合的对象?
答案 0 :(得分:1)
我认为问题在于你所谓的数组是1维的,而矩阵是2维的。
我们假设他们被称为M
和N
。 M.shape
提供(a,)
(正如您所说的那样#34;数组")N.shape
给出(a,b)
(正如您所说的那样"矩阵&# 34)。如果您执行M = M.reshape(a, 1)
,则会获得与N
和np.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)
使用None
或np.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))
在追加之前。