目录
np.column_stack?和?np.row_stack
np.hstack
?和?np.vstack
np.hstack
(水平堆叠)和 np.vstack
(垂直堆叠)是两个最常用的堆叠函数。
np.hstack
)import numpy as np
# 创建两个一维数组
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# 水平堆叠
h_stack = np.hstack((a, b))
print("Horizontal stack:\n", h_stack)
输出:
Horizontal stack: [1 2 3 4 5 6]
np.vstack
)# 垂直堆叠
v_stack = np.vstack((a, b))
print("Vertical stack:\n", v_stack)
输出:
Vertical stack: [[1 2 3] [4 5 6]]
np.concatenate
np.concatenate
是一个更通用的函数,它可以沿指定的轴堆叠多个数组。
# 沿第一个轴(垂直方向)堆叠
concat_0 = np.concatenate((a[:, np.newaxis], b[:, np.newaxis]), axis=0)
print("Concatenate along axis 0:\n", concat_0)
# 沿第二个轴(水平方向)堆叠
concat_1 = np.concatenate((a[:, np.newaxis], b[:, np.newaxis]), axis=1)
print("Concatenate along axis 1:\n", concat_1)
预期输出:
Concatenate along axis 0:
[[1] [2] [3] [4] [5] [6]]
Concatenate along axis 1:
[[1 4] [2 5] [3 6]]
np.column_stack
?和?np.row_stack
np.column_stack
类似于 np.hstack
,但它是专门为一维数组设计的,将一维数组作为列堆叠到二维数组中。np.row_stack
类似于 np.vstack
,用于堆叠行。
# 列堆叠
column_stack = np.column_stack((a, b))
print("Column stack:\n", column_stack)
# 行堆叠 6row_stack = np.row_stack((a, b))
print("Row stack:\n", row_stack)
输出:
Column stack:
[[1 4] [2 5] [3 6]]
Row stack:
[[1 2 3] [4 5 6]]
np.dstack
np.dstack
用于沿第三维度(深度方向)堆叠数组。
# 深度堆叠
d_stack = np.dstack((a, b))
print("Depth stack:\n", d_stack)
输出:
Depth stack: [[[1 4] [2 5] [3 6]]]
np.stack
np.stack
是一个通用的堆叠函数,允许你沿新的轴堆叠数组。
# 创建两个二维数组
a_2d = np.array([[1, 2], [3, 4]])
b_2d = np.array([[5, 6], [7, 8]])
# 沿新轴堆叠
new_stack = np.stack((a_2d, b_2d), axis=0)
print("Stack along new axis:\n", new_stack)
输出:
Stack along new axis:
?[[[1 2]
? ?[3 4]]
? [[5 6]
? ?[7 8]]]
?