NumPy 数组连接

连接数组常用的函数如下:

函数描述
concatenate连接沿现有轴的数组序列
stack沿着新的轴加入一系列数组。
hstack水平堆叠序列中的数组(列方向)
vstack竖直堆叠序列中的数组(行方向)
dstack沿高度堆叠,该高度与深度相同

按轴连接数组(numpy.concatenate)

连接意味着将两个或多个数组的内容放在单个数组中。
在 SQL 中,我们基于键来连接表,而在 NumPy 中,我们按轴连接数组。

numpy.concatenate 函数用于沿指定轴连接相同形状的两个或多个数组,格式如下:

numpy.concatenate((a1, a2, ...), axis)

参数说明:

a1, a2, ...:相同类型的数组axis:沿着它连接数组的轴,默认为 0

import numpy as np
a = np.array([[1,2,3,4,5],[3,4,5,6,7]])
print ('第一个数组:')
print (a)
print ('\n')
b = np.array([[5,6,7,8,9],[7,8,9,10,11]])
print ('第二个数组:')
print (b)
print ('\n')
 # 两个数组的维度相同
print ('沿轴 0 连接两个数组:')
print (np.concatenate((a,b)))
print ('\n')
print ('沿轴 1 连接两个数组:')
print (np.concatenate((a,b),axis = 1))

输出结果为:

[[ 5 6 7 8 9]
[ 7 8 9 10 11]]

沿轴 0 连接两个数组:
[[ 1 2 3 4 5]
[ 3 4 5 6 7]
[ 5 6 7 8 9]
[ 7 8 9 10 11]]

沿轴 1 连接两个数组:
[[ 1 2 3 4 5 5 6 7 8 9]
[ 3 4 5 6 7 7 8 9 10 11]]

使用堆栈函数连接数组(numpy.stack)

numpy.stack 函数用于沿新轴连接数组序列,格式如下:

numpy.stack(arrays, axis)

参数说明:

arrays相同形状的数组序列axis:返回数组中的轴,输入数组沿着它来堆叠

import numpy as np
a = np.array([[1,2,3,4,5],[3,4,5,6,7]])
print ('第一个数组:')
print (a)
print ('\n')
b = np.array([[5,6,7,8,9],[7,8,9,10,11]])
print ('第二个数组:')
print (b)
print ('\n')
print ('沿轴 0 堆叠两个数组:')
print (np.stack((a,b),0))
print ('\n')
print ('沿轴 1 堆叠两个数组:')
print (np.stack((a,b),1))

输出结果如下:

第一个数组:
[[1 2 3 4 5]
[3 4 5 6 7]]

第二个数组:
[[ 5 6 7 8 9]
[ 7 8 9 10 11]]

沿轴 0 堆叠两个数组:
[[[ 1 2 3 4 5]
[ 3 4 5 6 7]]
[[ 5 6 7 8 9]
[ 7 8 9 10 11]]]

沿轴 1 堆叠两个数组:
[[[ 1 2 3 4 5]
[ 5 6 7 8 9]]
[[ 3 4 5 6 7]
[ 7 8 9 10 11]]]

沿行堆叠数组(numpy.hstack)

numpy.hstack 是 numpy.stack 函数的变体,它通过水平堆叠来生成数组。

import numpy as np
a = np.array([[1,2,3,4,5],[3,4,5,6,7]])
print ('第一个数组:')
print (a)
print ('\n')
b = np.array([[5,6,7,8,9],[7,8,9,10,11]])
print ('第二个数组:')
print (b)
print ('\n')
print ('水平堆叠:')
c = np.hstack((a,b))
print (c)
print ('\n')

输出结果如下:

第一个数组:
[[1 2 3 4 5]
 [3 4 5 6 7]]

第二个数组:
[[ 5 6 7 8 9]
 [ 7 8 9 10 11]]

水平堆叠:
[[ 1 2 3 4 5 5 6 7 8 9]
 [ 3 4 5 6 7 7 8 9 10 11]]

沿列堆叠数组(numpy.vstack)

numpy.vstack 是 numpy.stack 函数的变体,它通过垂直堆叠来生成数组。

import numpy as np
a = np.array([[1,2,3,4,5],[3,4,5,6,7]])
print ('第一个数组:')
print (a)
print ('\n')
b = np.array([[5,6,7,8,9],[7,8,9,10,11]])
print ('第二个数组:')
print (b)
print ('\n')
print ('竖直堆叠:')
c = np.vstack((a,b))
print (c)

输出结果为:

第一个数组:
[[1 2 3 4 5]
 [3 4 5 6 7]]

第二个数组:
[[ 5 6 7 8 9]
 [ 7 8 9 10 11]]

竖直堆叠:
[[ 1 2 3 4 5]
 [ 3 4 5 6 7]
 [ 5 6 7 8 9]
 [ 7 8 9 10 11]]

沿高度堆叠(numpy.dstack)

NumPy 提供了一个辅助函数:dstack() 沿高度堆叠,该高度与深度相同。

import numpy as np
a = np.array([[1,2,3,4,5],[3,4,5,6,7]])
b = np.array([[5,6,7,8,9],[7,8,9,10,11]])
arr = np.dstack((a, b))
print(arr)

输出结果为:

[[[ 1 5]
  [ 2 6]
  [ 3 7]
  [ 4 8]
  [ 5 9]]

 [[ 3 7]
  [ 4 8]
  [ 5 9]
  [ 6 10]
  [ 7 11]]]