将形状相同的数组在指定维度上进行叠加
函数用法一个简单的二维数组的例子
>>> a = np.arange(9).reshape((3, 3))
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> b = np.arange(9, 18).reshape((3, 3))
>>> b
array([[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]])
>>> c = np.arange(18, 27).reshape((3, 3))
>>> c
array([[18, 19, 20],
[21, 22, 23],
[24, 25, 26]])
# 将a、b、c三个数组在轴axis=0上进行叠加,得到一个三维数组
>>> d = np.stack((a, b, c), axis=0)
>>> d
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
# 将a、b、c三个数组在轴axis=1上进行叠加,同样得到一个三维数组
>>> e = np.stack((a, b, c), axis=1)
>>> e
array([[[ 0, 1, 2],
[ 9, 10, 11],
[18, 19, 20]],
[[ 3, 4, 5],
[12, 13, 14],
[21, 22, 23]],
[[ 6, 7, 8],
[15, 16, 17],
[24, 25, 26]]])
>>> f = np.stack((a, b, c), axis=2)
>>> f
array([[[ 0, 9, 18],
[ 1, 10, 19],
[ 2, 11, 20]],
[[ 3, 12, 21],
[ 4, 13, 22],
[ 5, 14, 23]],
[[ 6, 15, 24],
[ 7, 16, 25],
[ 8, 17, 26]]])
再来看一个三维数组的例子
>>> a = np.zeros((2, 2, 2), dtype=int)
>>> a
array([[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]]])
>>> b = np.ones((2, 2, 2), dtype=int)
>>> b
array([[[1, 1],
[1, 1]],
[[1, 1],
[1, 1]]])
>>> c = np.full((2, 2, 2), 2, dtype=int)
>>> c
array([[[2, 2],
[2, 2]],
[[2, 2],
[2, 2]]])
# 在轴axis=0上进行堆叠
>>> d = np.stack((a, b, c), axis=0)
>>> d
array([[[[0, 0],
[0, 0]],
[[0, 0],
[0, 0]]],
[[[1, 1],
[1, 1]],
[[1, 1],
[1, 1]]],
[[[2, 2],
[2, 2]],
[[2, 2],
[2, 2]]]])
>>> d.shape
(3, 2, 2, 2)
>>> e = np.stack((a, b, c), axis=1)
>>> e
array([[[[0, 0],
[0, 0]],
[[1, 1],
[1, 1]],
[[2, 2],
[2, 2]]],
[[[0, 0],
[0, 0]],
[[1, 1],
[1, 1]],
[[2, 2],
[2, 2]]]])
>>> e.shape
(2, 3, 2, 2)
# 在轴axis=2上进行堆叠
>>> f = np.stack((a, b, c), axis=2)
>>> f
array([[[[0, 0],
[1, 1],
[2, 2]],
[[0, 0],
[1, 1],
[2, 2]]],
[[[0, 0],
[1, 1],
[2, 2]],
[[0, 0],
[1, 1],
[2, 2]]]])
>>> f.shape
(2, 2, 3, 2)
# 相当于g = np.stack((a, b, c), axis=-1)
>>> g = np.stack((a, b, c), axis=3)
>>> g
array([[[[0, 1, 2],
[0, 1, 2]],
[[0, 1, 2],
[0, 1, 2]]],
[[[0, 1, 2],
[0, 1, 2]],
[[0, 1, 2],
[0, 1, 2]]]])
>>> g.shape
(2, 2, 2, 3)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)