concatenate函數


numpy.concatenate((a1, a2, ...), axis=0)

Join a sequence of arrays along an existing axis.(按軸axis連接array組成一個新的array)

The arrays must have the same shape, except in the dimension corresponding to axis

axis:default is 0

>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])               b是一個二維array
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.concatenate((a, b.T), axis=1)
array([[1, 2, 5],
       [3, 4, 6]])


>>> b = np.array([[5,6]])         可以看出b是二維的不是一維的
>>> b.shape
(1, 2)
>>> b = np.array([5,6])
>>> b.shape
(2,)


 

更普通的例子

>>> a = np.array([[1, 2], [3, 4]])                a、b的shape為(2,2),連接第一維就變成(4,2),連接第二維就變成(2,4)
>>> b = np.array([[5, 6], [7, 8]])
>>> np.concatenate((a,b),axis=0)
array([[1, 2],
       [3, 4],
       [5, 6],
       [7, 8]])
>>> np.concatenate((a,b),axis=1)
array([[1, 2, 5, 6],
       [3, 4, 7, 8]])

>>> c = np.concatenate((a,b),axis=1)
>>> c
array([[1, 2, 5, 6],
       [3, 4, 7, 8]])
>>> c.shape
(2, 4)

 

concatenate([a, b])

連接,連接后ndim不變,a和b可以有一維size不同,但size不同的維度必須是要連接的維度

例如,a.shape為(4,5,6,10),b.shape為(4,5,6,20)

np.concatenate([a,b], axis=3) # 返回張量的shape為(4,5,6,30)



有助於理解的例子。第一個例子是一維的,這一維全是數字,第二個例子是二維的,實際上可以看作將數字換成向量的一維的array。第一個例子axis=0把所有的數字
連接,第二個例子axis=0就可以把所有的向量連接。第二個例子中axis=1,這表明axis=0的個數不發生變化,只變化axis=1。axis=0不發生變化,那兩個array對
應的axis=0的元素就可以進行連接。這兩個array中的元素是一維向量,就對一維向量進行連接(其實這時候就相當於第一個例子中的連接了)。
若把axis=1中的數字換成一維向量就可以推廣到3維的axis=1時的變化,若換到更高維可以推廣到更高維的變化。

>>> a=np.array([1,2,3])
>>> b=np.array([11,22,33])
>>> c=np.array([44,55,66])
>>> np.concatenate((a,b,c),axis=0)  
array([ 1,  2,  3, 11, 22, 33, 44, 55, 66]) 

 

>>> a=np.array([[1,2,3],[4,5,6]])
>>> b=np.array([[11,21,31],[7,8,9]])
>>> np.concatenate((a,b),axis=0)
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [11, 21, 31],
       [ 7,  8,  9]])

>>> np.concatenate((a,b),axis=1)  
array([[ 1,  2,  3, 11, 21, 31],
       [ 4,  5,  6,  7,  8,  9]])

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM