np.concatenate
是一个将数组拼接起来的函数,具体怎么拼接,可以看一下一维和二维的例子,具体高维的直推就行了。
一、一维数组
import numpy as np
a = np.array([1,2,3])
b = np.array([11,22,33])
jointArray = np.concatenate((a, b), axis=0) # 按数组的第一维进行拼接
print('a=', a)
print('b=', b)
print('jointArray=', jointArray)
二、二维数组
2.1 连接第一维
np.concatenate((a1, a2), axis = 0);
例子:
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
jointArray = np.concatenate((a, b), axis=0) # axis = 0第一维拼接
print('a=', a)
print('b=', b)
print('jointArray=', jointArray)
a= [[1 2] [3 4]] b= [[5 6]] jointArray = [[1 2] [3 4]
[5 6]]
注意:在Python中,[1, 2]
和[[1, 2]]
是有区别的,可以看一下:
import numpy as np
b = np.array([[1, 2]])
c = np.array([1, 2])
print(b.shape)
print(c.shape)
(1, 2)
(2,)
2.2 连接第二维
import numpy as np
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
jointArray = np.concatenate((a, b.T), axis=1) # 要将行向量b转置为列向量
print('a=', a)
print('b=', b)
print('jointArray=', jointArray)
a= [[1 2]
[3 4]]
b= [[5 6]]
jointArray= [[1 2 5]
[3 4 6]]
三、np.contenate降维
两个数组是进行拼接,如果只有一个数组a
的话就是用来降维的,看一下例子:
import numpy as np
a = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]])
b = np.concatenate(a, axis=0)
c = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
d = np.concatenate(c, axis=0)
print('a =', a.shape)
print('b =', b.shape)
print('c =', c.shape)
print('d =', d.shape)
a = (3, 2, 2)
b = (6, 2)
c = (2, 5)
d = (10,)