读书笔记 numpy入门 第2章 数组拼接

np.concatenate

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

x = np.array([1, 2, 3])
y = np.array([3, 2, 1])
np.concatenate([x, y])

array([1, 2, 3, 3, 2, 1])

# 拼接3个数组
z = [99, 99, 99]
print(np.concatenate([x, y, z]))

[ 1 2 3 3 2 1 99 99 99]

二维数组拼接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
grid = np.array([[1, 2, 3],
[4, 5, 6]])

# 沿着第一个轴拼接
np.concatenate([grid, grid])

array([[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6]])

# 沿着第二个轴拼接(从0开始索引)
np.concatenate([grid, grid], axis=1)

array([[1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6]])

https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html

np.vstack

1
2
3
4
5
6
7
8
9
10
x = np.array([1, 2, 3])
grid = np.array([[9, 8, 7],
[6, 5, 4]])

# 垂直栈数组
np.vstack([x, grid])

array([[1, 2, 3],
[9, 8, 7],
[6, 5, 4]])

https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html

np.hstack

1
2
3
4
5
6
7
# 水平栈数组
y = np.array([[99],
[99]])
np.hstack([grid, y])

>>> array([[ 9, 8, 7, 99],
[ 6, 5, 4, 99]])

https://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html

np.dstack

https://www.numpy.org/devdocs/reference/generated/numpy.dstack.html

沿着第三个维度拼接数组

1
2
3
4
5
6
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
>>>array([[[1, 2],
[2, 3],
[3, 4]]])