# 【3】数据分析-1-数据的处理--numpy--9--Numpy中stack()，vstack(), hstack()函数区别

## 一、 stack()函数

import numpy as np
a=[[[1,2,3,4],[11,21,31,41]],
[[5,6,7,8],[51,61,71,81]],
[[9,10,11,12],[91,101,111,121]]]
print("列表a如下：")
print(a)

print("新维度的下标为0")
c=np.stack(a,axis=0)
print(c)

print("新维度的下标为1")
c=np.stack(a,axis=1)
print(c)

print("新维度的下标为2")
c=np.stack(a,axis=2)
print(c)


列表a如下：
[[[1, 2, 3, 4], [11, 21, 31, 41]], [[5, 6, 7, 8], [51, 61, 71, 81]], [[9, 10, 11, 12], [91, 101, 111, 121]]]

[[[  1   2   3   4]
[ 11  21  31  41]]

[[  5   6   7   8]
[ 51  61  71  81]]

[[  9  10  11  12]
[ 91 101 111 121]]]

[[[  1   2   3   4]
[  5   6   7   8]
[  9  10  11  12]]

[[ 11  21  31  41]
[ 51  61  71  81]
[ 91 101 111 121]]]

[[[  1   5   9]
[  2   6  10]
[  3   7  11]
[  4   8  12]]

[[ 11  51  91]
[ 21  61 101]
[ 31  71 111]
[ 41  81 121]]]


stack(a, axis=1), 个人理解，就是将数组中元素第0个维度的数值换到第1维度。如31就由[0,1,2]变为[1,0,2]，41就由[0,1,3]变为[1,0,3], 8就由[1,0,3]变为[0,1,3]，以此类推。所以数组的shape就变为了(2,3,4)

stack(a, axis=2) , 就是将数组中每个元素的第0个维度的索引值移到第2维度，原先的第1，第2维的索引值一起前移。如31就由[0,1,2]变为[1,2,0]，41就由[0,1,3]变为[1,3,0],8就由[1,0,3]变为[0,3,1]，以此类推。所以数组的shape就变为了(2,4,3)

## 2. hstack()函数

a = np.array([1,2,3])
b = np.array([4,5,6])
c=[[[1,2,3,4],[11,21,31,41]],
[[5,6,7,8],[51,61,71,81]],
[[9,10,11,12],[91,101,111,121]]]
print('一维数组：')
print(np.hstack((a,b)))

a = np.array([[1],[2],[3]])
b = np.array([[4],[5],[6]])
print('二维数组：')
print(np.hstack((a,b)))

a = np.array([[[1],[11]],
[[2],[21]],
[[3],[31]]])

b = np.array([[[4],[41]],
[[5],[51]],
[[6],[61]]])
print('三维数组：')
print(np.hstack((a,b)))

print('三维数组2：')
print(np.hstack(c))


一维数组：
[1 2 3 4 5 6]

[[1 4]
[2 5]
[3 6]]

[[[ 1]
[11]
[ 4]
[41]]

[[ 2]
[21]
[ 5]
[51]]

[[ 3]
[31]
[ 6]
[61]]]

[[  1   2   3   4   5   6   7   8   9  10  11  12]
[ 11  21  31  41  51  61  71  81  91 101 111 121]]


## 3. vstack()函数

a = np.array([1,2,3])
b = np.array([4,5,6])
c=[[[1,2,3,4],[11,21,31,41]],
[[5,6,7,8],[51,61,71,81]],
[[9,10,11,12],[91,101,111,121]]]
print('一维数组：')
print(np.vstack((a,b)))

a = np.array([[1],[2],[3]])
b = np.array([[4],[5],[6]])
print('二维数组：')
print(np.vstack((a,b)))

a = np.array([[[1],[11]],
[[2],[21]],
[[3],[31]]])

b = np.array([[[4],[41]],
[[5],[51]],
[[6],[61]]])
print('三维数组：')
print(np.vstack((a,b)))

print('三维数组2：')
print(np.vstack(c))


一维数组：
[[1 2 3]
[4 5 6]]

[[1]
[2]
[3]
[4]
[5]
[6]]

[[[ 1]
[11]]

[[ 2]
[21]]

[[ 3]
[31]]

[[ 4]
[41]]

[[ 5]
[51]]

[[ 6]
[61]]]

[[  1   2   3   4]
[ 11  21  31  41]
[  5   6   7   8]
[ 51  61  71  81]
[  9  10  11  12]
[ 91 101 111 121]]


## 参考资料

https://my.oschina.net/amui/blog/1601432

About Sam