Numpy 连接数组函数

numpy 连接数组函数:

  • concatenate : 连接沿现有轴的数组序列
  • stack : 沿着新的轴加入一系列数组。
  • hstack : 水平堆叠序列中的数组(列方向)
  • vstack : 竖直堆叠序列中的数组(行方向)

numpy.concatenate

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

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

参数说明:

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

实例

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

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


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


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


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

numpy.stack

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

numpy.stack(arrays, axis)

参数说明:

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

实例


import numpy as np
 
a = np.array([[1,2],[3,4]])
 
print ('第一个数组:')
print (a)
print ('\n')
b = np.array([[5,6],[7,8]])
 
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 6]
 [7 8]]


沿轴 0 堆叠两个数组:
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]


沿轴 1 堆叠两个数组:
[[[1 2]
  [5 6]]

 [[3 4]
  [7 8]]]

numpy.hstack

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

实例

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

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


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


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

numpy.vstack

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

实例

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

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


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


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