【python学习】numpy中的vstack、hstack、dstack三种堆叠函数的区别

numpy中的vstack、hstack、dstack三种堆叠函数的区别

先假设有以下的数据(用作示范三种函数返回的结果)

import numpy as np

data1 = [
[[11, 12, 13], [14, 15, 16], [17, 18, 19]],
[[21, 22, 23], [24, 25, 26], [27, 28, 29]],
[[31, 32, 33], [34, 35, 36], [37, 38, 39]]
]

data2 = [
[[41, 42, 43], [44, 45, 46], [47, 48, 49]],
[[51, 52, 53], [54, 55, 56], [57, 58, 59]],
[[61, 62, 63], [64, 65, 66], [67, 68, 69]]
]

arr1 = np.array(data1)
arr2 = np.array(data2)
# arr1.shape == [3, 3, 3]
# arr2.shape == [3, 3, 3]

vstack() 函数

vstack() 函数表示将数组在第一维上进行堆叠(即最外层的方括号),可将arr1和arr2第一维内的部分看作一个整体,即:

arr1 == [1], 
arr2 == [2]
vstack((arr1, arr2)) == [1 +2]

则使用vstack函数:

a = np.vstack((arr1, arr2))
print(a)
# 结果如下
[
[[11, 12, 13], [14, 15, 16], [17, 18, 19]],
[[21, 22, 23], [24, 25, 26], [27, 28, 29]],
[[31, 32, 33], [34, 35, 36], [37, 38, 39]],
[[41, 42, 43], [44, 45, 46], [47, 48, 49]],
[[51, 52, 53], [54, 55, 56], [57, 58, 59]],
[[61, 62, 63], [64, 65, 66], [67, 68, 69]]
]
# 此时 a.shape == [6, 3, 3]

hstack() 函数

hstack() 函数表示将数组在第二维进行堆叠(即第二层方括号),可将arr1和arr2中第二层括号里面的内容看作一个整体,即

arr1 == [
[1],
[2],
[3]
]

arr2 == [
[4],
[5],
[6]
]

# 然后 hstack((arr1, arr2)) 的结果如下:
[
[1 +4],
[2 +5],
[3 +6]
]

使用hstack() 函数,得到:

b = np.hstack((arr1, arr2))
print(b)
# 结果如下:
[
[[11, 12, 13], [14, 15, 16], [17, 18, 19], [41, 42, 43], [44, 45, 46], [47, 48, 49]],
[[21, 22, 23], [24, 25, 26], [27, 28, 29], [51, 52, 53], [54, 55, 56], [57, 58, 59]],
[[31, 32, 33], [34, 35, 36], [37, 38, 39], [61, 62, 63], [64, 65, 66], [67, 68, 69]]
]
# 此时 b.shape == [3, 6, 3]

dstack() 函数

dstack() 函数表示将数组在第三维进行堆叠(即第三层方括号),可将arr1和arr2第三层括号里面的内容看作一个整体,即:

arr1 = [
[[1], [2], [3]],
[[4], [5], [6]],
[[7], [8], [9]]
]

arr2 = [
[[11], [12], [13]],
[[14], [15], [16]],
[[17], [18], [19]]
]

# 然后 dstack((arr1, arr2)) 的结果如下:
[
[[1 +11],[2 +12],[3 +13]]
[[4 +14],[5 +15],[6 +16]]
[[7 +17],[8 +18],[9 +19]]
]

使用dstack() 函数,得到:


print(c)
# 结果如下:
[
[[11 12 13 41 42 43],[14 15 16 44 45 46],[17 18 19 47 48 49]]
[[21 22 23 51 52 53],[24 25 26 54 55 56],[27 28 29 57 58 59]]
[[31 32 33 61 62 63],[34 35 36 64 65 66],[37 38 39 67 68 69]]
]

# 此时 c.shape == [3, 3, 6]

以上内容参考链接文章
参考文档

你可能感兴趣的:(python学习)