np.concatenate 是numpy中对array进行拼接的函数,使用方法如下所示:
import numpy as np
x1 = np.random.normal(1,1,(5,4))
x2 = np.random.normal(1,1,(3,4))
print(x1)
print(x1.shape)
print(x2)
print(x2.shape)
con = np.concatenate([x1,x2],axis=0)
print(con)
print(con.shape)
输出结果为:
[[ 2.22806658 0.15277615 2.21245262 1.63831116]
[ 1.30131232 -1.09226289 -0.65959394 1.16066688]
[ 1.52737722 0.84587186 1.53041503 0.4584277 ]
[ 1.56096219 1.29506244 3.08048523 2.06008988]
[ 1.79964236 0.95087117 1.30845477 -0.2644263 ]]
(5, 4)
[[0.89383392 1.49502055 2.90571116 1.71943997]
[1.44451535 1.87838383 1.4763242 0.82597179]
[0.72629108 1.42406398 1.35519112 0.58121617]]
(3, 4)
[[ 2.22806658 0.15277615 2.21245262 1.63831116]
[ 1.30131232 -1.09226289 -0.65959394 1.16066688]
[ 1.52737722 0.84587186 1.53041503 0.4584277 ]
[ 1.56096219 1.29506244 3.08048523 2.06008988]
[ 1.79964236 0.95087117 1.30845477 -0.2644263 ]
[ 0.89383392 1.49502055 2.90571116 1.71943997]
[ 1.44451535 1.87838383 1.4763242 0.82597179]
[ 0.72629108 1.42406398 1.35519112 0.58121617]]
(8, 4)
axis参数为指定按照哪个维度进行拼接,上述的例子中x1为[5,4] x2为[3,4],设置axis=0则代表着按照第一维度进行拼接,拼接后的尺寸为[8,4]除了第一维度的尺寸发生变化,其他维度不变,同时也说明,必须保证其他维度的尺寸是能对的上的,如果x1为[5,4],x2为[5,3],在这里如果还设置axis=1的话,则会报错,因为x1和x2的第二维度尺寸不相等,无法拼接。
按照axis=1的维度进行拼接,实例如下:
import numpy as np
x1 = np.random.normal(1,1,(5,4))
x2 = np.random.normal(1,1,(5,2))
print(x1)
print(x1.shape)
print(x2)
print(x2.shape)
con = np.concatenate([x1,x2],axis=1)
print(con)
print(con.shape)
输出结果如下:
[[ 1.06700795 2.49432822 0.13721596 0.86647501]
[-0.24454185 0.83414428 2.06012125 -0.63322426]
[ 2.01993142 -0.27599932 1.9101389 1.92564214]
[ 0.12627442 0.97560762 2.00993226 2.02754602]
[ 0.23883256 1.4805339 -0.83029287 1.37207756]]
(5, 4)
[[ 0.67988459 2.46464482]
[ 1.19166015 2.16522311]
[ 1.41193468 -0.01165058]
[ 0.62496307 1.05706225]
[ 0.85055712 -0.09588572]]
(5, 2)
[[ 1.06700795 2.49432822 0.13721596 0.86647501 0.67988459 2.46464482]
[-0.24454185 0.83414428 2.06012125 -0.63322426 1.19166015 2.16522311]
[ 2.01993142 -0.27599932 1.9101389 1.92564214 1.41193468 -0.01165058]
[ 0.12627442 0.97560762 2.00993226 2.02754602 0.62496307 1.05706225]
[ 0.23883256 1.4805339 -0.83029287 1.37207756 0.85055712 -0.09588572]]
(5, 6)
这个例子中的x1为[5,4],x2为[5,2]按照axis=1进行拼接,拼接后的尺寸为[5,6]