源代码中给的例子:
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> b = np.array([[5, 6]])
>>> np.concatenate((a, b), axis=0)
array([[1, 2],
[3, 4],
[5, 6]])
"""
a=> (2,2)
b=> (1,2)
如果是第二维要拼接,其他维度需要同一样的维度,所以b需要转置。b=> (2,1)
"""
>>> np.concatenate((a, b.T), axis=1) #所以b需要转置。b=> (2,1)
array([[1, 2, 5],
[3, 4, 6]])
>>> np.concatenate((a, b), axis=None)
array([1, 2, 3, 4, 5, 6])
axis=0:在第一维拼接:其他维度的需要是相同的维度;
axis=1:在第二维拼接:其他维度的需要是相同的维度;
axis=-1:最后一维拼接:其他维度的需要是相同的维度;
import numpy as np
"""
a=> a的维度:(3, 2, 2)
b=> b的维度:(3, 2, 2)
"""
a=np.array([
[[1,2],[3,4]],
[[5,6],[7,8]],
[[8,9],[8,9]]
])
b=np.array([
[[1,2],[2,3]],
[[4,5],[4,5]],
[[5,6],[6,7]]
])
print(a.shape)
print(b.shape)
print("=================================")
res1=np.concatenate((a,b),axis=0)
print(res1.shape)
print(res1)
print("=================================")
res2=np.concatenate((a,b),axis=1)
print(res2.shape)
print(res2)
print("=================================")
res3=np.concatenate((a,b),axis=-1)
print(res3.shape)
print(res3)
=================================
(6, 2, 2) axis=0
[[[1 2]
[3 4]]
[[5 6]
[7 8]]
[[8 9]
[8 9]]
[[1 2]
[2 3]]
[[4 5]
[4 5]]
[[5 6]
[6 7]]]
=================================
(3, 4, 2) axis=1
[[[1 2]
[3 4]
[1 2]
[2 3]]
[[5 6]
[7 8]
[4 5]
[4 5]]
[[8 9]
[8 9]
[5 6]
[6 7]]]
=================================
(3, 2, 4) axis=-1
[[[1 2 1 2]
[3 4 2 3]]
[[5 6 4 5]
[7 8 4 5]]
[[8 9 5 6]
[8 9 6 7]]]
注意:如果需要拼接某一维度,那其维度的维数要相同。当a,b是二维数组时,axis=1 和axis=-1操作的都是最后一维。
a = np.array([[1, 2], [3, 4]]) #(2,2)
b = np.array([[5, 6]]) #(1,2)
res4=np.concatenate((a,b),axis=0)
print("res4:",res4.shape)
res5=np.concatenate((a,b.T),axis=1)
print("res5:",res5.shape)
********************************
res4: (3, 2) ==>(2+1=3, 2)
res5: (2, 3) ===>(2,2+1=3)
res6: (2, 3) ===>(2,2+1=3)