import numpy as np
# stack()是按照不同轴的堆叠方式重新堆叠数组
a=[[1,2,3],[4,5,6]]
np.stack(a,axis=0)
# array([[1, 2, 3],
# [4, 5, 6]])
np.stack(a,axis=1)
# array([[1, 4],
# [2, 5],
# [3, 6]])
#可以看出axis=0是把原来的元素按照横轴的方式排列,axis=1是把原先元素按照纵轴排列
# 更多的例子
a=[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
np.stack(a,axis=0)
#array([[ 1, 2, 3, 4],
# [ 5, 6, 7, 8],
# [ 9, 10, 11, 12]])
np.stack(a,axis=1)
#array([[ 1, 5, 9],
# [ 2, 6, 10],
# [ 3, 7, 11],
# [ 4, 8, 12]])
a=[1,2,3,4]
b=[5,6,7,8]
c=[9,10,11,12]
np.stack((a,b,c),axis=0)
#array([[ 1, 2, 3, 4],
# [ 5, 6, 7, 8],
# [ 9, 10, 11, 12]])
np.stack((a,b,c),axis=1)
#array([[ 1, 5, 9],
# [ 2, 6, 10],
# [ 3, 7, 11],
# [ 4, 8, 12]])
a=[[1,2,3],[4,5,6]]
b=[[7,8,9],[10,11,12]]
c=[[13,14,15],[16,17,18]]
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]]])
#hstack()、vstack()是按元素进行堆叠而不是数组的形状堆叠,具体与stack的区别后面有个例子
a=[1,2,3]
b=[4,5,6]
np.hstack((a,b))
#array([1, 2, 3, 4, 5, 6])
np.vstack((a,b))
#array([[1, 2, 3],
# [4, 5, 6]])
#我们来看一下这三个函数对于复杂的矩阵堆叠的区别
a=[[1],[2],[3]]
b=[[4],[5],[6]]
c=[[7],[8],[9]]
np.stack((a,b,c),axis=0)
#array([[[1],
# [2],
# [3]],
# [[4],
# [5],
# [6]],
# [[7],
# [8],
# [9]]])
np.stack((a,b,c),axis=1)
#array([[[1],
# [4],
# [7]],
# [[2],
# [5],
# [8]],
# [[3],
# [6],
3 [9]]])
np.hstack((a,b,c))
#array([[1, 4, 7],
# [2, 5, 8],
# [3, 6, 9]])
np.vstack((a,b,c))
#array([[1],
# [2],
# [3],
# [4],
# [5],
# [6],
# [7],
# [8],
# [9]])
#再来看一个
a=[[1,2,3],[4,5,6]]
b=[[7,8,9],[10,11,12]]
c=[[13,14,15],[16,17,18]]
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.hstack((a,b,c))
#array([[ 1, 2, 3, 7, 8, 9, 13, 14, 15],
# [ 4, 5, 6, 10, 11, 12, 16, 17, 18]])
np.vstack((a,b,c))
#array([[ 1, 2, 3],
# [ 4, 5, 6],
# [ 7, 8, 9],
# [10, 11, 12],
# [13, 14, 15],
# [16, 17, 18]])
#可以看出stack是在不破坏原有矩阵形状的情况下按照横或纵的方式堆叠,hstack和vstack更进一步,打破了原有矩阵的结构