np.concatenate函数

numpy.concatenate((a1a2...)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]])

猜你喜欢

转载自blog.csdn.net/IAlexanderI/article/details/87903339