numpy stack vstack hstack concatenate

基本都用作連接字符串,只是連接維度不同,而且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]])
#按照維度,如果axis = 2, 就是dim = 2的情況分解矩陣並連接
#將按第0維的個數,分別將第2維相對應位置的數字合併成一個小數組。該數組長度爲shape[0]
#同理,當axis=1,按第0維個數,將第1維相應的數組合並,合併後的數組也是shape[0]的長度,
#如[[ 1,  2,  3],
#        [11, 12, 13]],就是分別從shape[0]下的第1維的[1,2,3]和[11,12,13]合併得到,長度爲shape[0]
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)))
#np.concatenate axis = 0 is vstack
#np.concatenate axis = 1 is hstack
('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]]))
# 類似於np.stack(*****, axis=2)
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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章