爲什麼np.hstack([matrix, vector])
不工作的原因是因爲形狀不適合對方:
>>> vector.shape
(6,)
>>> matrix.shape
(6, 5)
但是,如果你讓一個vector
列矢量與vector[:, np.newaxis]
然後np.hstack
可以處理形狀:
>>> matrix = np.arange(30).reshape(6,5)
>>> vector = -np.ones(6)
>>> matrix
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]])
>>> vector
array([-1., -1., -1., -1., -1., -1.])
>>> vector[:, np.newaxis]
array([[-1.],
[-1.],
[-1.],
[-1.],
[-1.],
[-1.]])
>>> vector[:, np.newaxis].shape
(6, 1)
>>> np.hstack([matrix, vector])
Rückverfolgung (innerste zuletzt):
Python-Shell, prompt 23, line 1
File "C:\Python34\Lib\site-packages\numpy\core\shape_base.py", line 293, in hstack
return _nx.concatenate(arrs, 1)
builtins.ValueError: all the input arrays must have same number of dimensions
>>> np.hstack([matrix, vector[:, np.newaxis]])
array([[ 0., 1., 2., 3., 4., -1.],
[ 5., 6., 7., 8., 9., -1.],
[ 10., 11., 12., 13., 14., -1.],
[ 15., 16., 17., 18., 19., -1.],
[ 20., 21., 22., 23., 24., -1.],
[ 25., 26., 27., 28., 29., -1.]])
'np.concatenate'怎麼樣? – jadsq