np.vstack(),np.hstack()和np.stack()的区别
示例数据:
a = np.arange(1,7).reshape((2,3))
b = np.arange(7,13).reshape((2,3))
c = np.arange(13,19).reshape((2,3))
print(a)
print(b)
print(c)
a:
[[1 2 3]
[4 5 6]]
b:
[[ 7 8 9]
[10 11 12]]
c:
[[13 14 15]
[16 17 18]]
一、np.vstack()
numpy.vstack(tup)
tup : sequence of ndarrays
Stack arrays in sequence vertically (row wise)
np.vstack():在竖直方向上堆叠
np.vstack((a,b,c))
array(
[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])
二、np.hstack()
numpy.hstack(tup)
其中tup是arrays序列,tup : sequence of ndarrays
Stack arrays in sequence horizontally (column wise).
np.hstack():在水平方向上平铺
np.hstack((a,b,c))
array(
[[ 1, 2, 3, 7, 8, 9, 13, 14, 15],
[ 4, 5, 6, 10, 11, 12, 16, 17, 18]])
三、np.stack()
这里是官方文档传送门:
https://numpy.org/doc/stable/reference/generated/numpy.stack.html
numpy.stack(arrays, axis)
参数:
arrays :[数组]相同形状的数组序列。
axis :[int]输入数组沿其堆叠的结果数组中的轴。
Return :[stacked ndarray]输入数组的堆栈数组,其维数比输入数组大。`
stack()函数是将arrays里面的每个元素(列表,元组,或者numpy的数组)变成numpy的数组后,再对每个元素增加一个维度(靠axis控制),然后再将这些元素串起来。
axis代表在哪个维度上加一维
np.stack((a,b,c),axis = 0)
array(
[[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]],
[[13, 14, 15],
[16, 17, 18]]])
np.stack((a,b,c),axis = 1)
array(
[[[ 1, 2, 3],
[ 7, 8, 9],
[13, 14, 15]],
[[ 4, 5, 6],
[10, 11, 12],
[16, 17, 18]]])
np.stack((a,b,c),axis = 2)
array
([[[ 1, 7, 13],
[ 2, 8, 14],
[ 3, 9, 15]],
[[ 4, 10, 16],
[ 5, 11, 17],
[ 6, 12, 18]]])