基本都用作連接字符串,只是連接維度不同,而且hstack和vstack 相對於stack,不受兩個字符串shape必須相同的限制。
import numpy as np
test_1 = np.array([[1, 2, 3], [4, 5, 6]])
test_2 = np.array([[11, 12, 13], [14, 15, 16]])
print('axis=2',np.stack((test_1, test_2), axis=2))
print('axis=1',np.stack((test_1, test_2), axis=1))
print('axis=0',np.stack((test_1, test_2), axis=0))
print('concat axis=1',np.concatenate((test_1,test_2),1))
print('hstack',np.hstack((test_1,test_2)))
print('concat axis=0',np.concatenate((test_1,test_2),0))
print('vstack',np.vstack((test_1,test_2)))
('axis=2', array([[[ 1, 11],
[ 2, 12],
[ 3, 13]],
[[ 4, 14],
[ 5, 15],
[ 6, 16]]]))
('axis=1', array([[[ 1, 2, 3],
[11, 12, 13]],
[[ 4, 5, 6],
[14, 15, 16]]]))
('axis=0', array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[11, 12, 13],
[14, 15, 16]]]))
('concat axis=1', array([[ 1, 2, 3, 11, 12, 13],
[ 4, 5, 6, 14, 15, 16]]))
('hstack', array([[ 1, 2, 3, 11, 12, 13],
[ 4, 5, 6, 14, 15, 16]]))
('concat axis=0', array([[ 1, 2, 3],
[ 4, 5, 6],
[11, 12, 13],
[14, 15, 16]]))
('vstack', array([[ 1, 2, 3],
[ 4, 5, 6],
[11, 12, 13],
[14, 15, 16]]))
test_1 = np.array([[1, 2, 3], [4, 5, 6]])
t = np.arange(1, 3).reshape((-1, 1))
print(np.hstack((t, test_1 )))
print t
print np.stack((t,test_1), axis = 2)
[[1 1 2 3]
[2 4 5 6]]
[[1]
[2]]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-5-8375b98d2dd9> in <module>()
4 print(np.hstack((t, test_1 )))
5 print t
----> 6 print np.stack((t,test_1), axis = 2)
/Users/eclipsycn/anaconda2/lib/python2.7/site-packages/numpy/core/shape_base.pyc in stack(arrays, axis)
352 shapes = set(arr.shape for arr in arrays)
353 if len(shapes) != 1:
--> 354 raise ValueError('all input arrays must have the same shape')
355
356 result_ndim = arrays[0].ndim + 1
ValueError: all input arrays must have the same shape