06_NumPy的数组变形与级联合并

一、变形

  • 使用reshape函数
# 创建一个20个元素的一维数组
n = np.arange(1,21)
n
# 执行结果
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
       18, 19, 20])

# 查看形状
print(n.shape)
# 执行结果
(20,)

# reshape:将数组改变形状
# 将n变成4行5列的二维数组
n2 = np.reshape(n,(4,5))
print(n2)
# 执行结果
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]]
   
print(n2.shape)
# 执行结果
(4, 5)
 
# 将n2变成5行4列的二维数组
# n2.reshape(5,4)
print(n2.reshape((5,4)))
# 执行结果
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]
 [17 18 19 20]]

# 注意:变形的过程中需要保持元素个数一致
# n2.reshape((5,5))   # 20个元素变形成25个则报错

# 还原成一维数组
print(n2.reshape(20))
# 执行结果
[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20]
print(n2.reshape(-1))
# 执行结果
[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20]

# 使用-1:表明任意剩余维度长度
print(n2.reshape(4,-1))
# 执行结果
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]]
 
print(n2.reshape(5,-1))
# 执行结果
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]
 [17 18 19 20]]
 
print(n2.reshape(-1,2))
# 执行结果
[[ 1  2]
 [ 3  4]
 [ 5  6]
 [ 7  8]
 [ 9 10]
 [11 12]
 [13 14]
 [15 16]
 [17 18]
 [19 20]]
 
print(n2.reshape(-1,1))
# 执行结果
[[ 1]
 [ 2]
 [ 3]
 [ 4]
 [ 5]
 [ 6]
 [ 7]
 [ 8]
 [ 9]
 [10]
 [11]
 [12]
 [13]
 [14]
 [15]
 [16]
 [17]
 [18]
 [19]
 [20]]

# 不能使用两个-1
# print(n2.reshape(-1,-1))
n2.reshape(2,-1,2)
# 执行结果
array([[[ 1,  2],
        [ 3,  4],
        [ 5,  6],
        [ 7,  8],
        [ 9, 10]],

       [[11, 12],
        [13, 14],
        [15, 16],
        [17, 18],
        [19, 20]]])

二、np.concatenate()

  • 参数是列表或元组
  • 级联的数组维度必须一样
  • 可通过axis参数改变级联的方向
# 创建两个二维数组
n1 = np.random.randint(0,100,size=(3,5))
n2 = np.random.randint(0,100,size=(3,5))
display(n1,n2)
# 执行结果
array([[12, 38, 49, 56, 52],
       [91, 43, 59, 18, 42],
       [23, 46, 95, 74, 81]])
array([[70, 42, 63, 86, 86],
       [73, 55, 45,  5, 89],
       [44, 47, 77, 58, 84]])

# 级联(合并),默认上下合并
# np.concatenate((n1,n2))
#上下合并 axis=0 表明第一个维度(行)
np.concatenate((n1,n2),axis=0)
# 执行结果
array([[12, 38, 49, 56, 52],
       [91, 43, 59, 18, 42],
       [23, 46, 95, 74, 81],
       [70, 42, 63, 86, 86],
       [73, 55, 45,  5, 89],
       [44, 47, 77, 58, 84]])
       
# 左右合并 axis=1 表明第二个维度(列)
np.concatenate((n1,n2),axis=1)
# 执行结果
array([[12, 38, 49, 56, 52, 70, 42, 63, 86, 86],
       [91, 43, 59, 18, 42, 73, 55, 45,  5, 89],
       [23, 46, 95, 74, 81, 44, 47, 77, 58, 84]])

三、np.hstack() 与 np.vstack()

  • 水平级联与垂直级联
# np.hstack:水平级联
np.hstack((n1,n2))
# 执行结果
array([[12, 38, 49, 56, 52, 70, 42, 63, 86, 86],
       [91, 43, 59, 18, 42, 73, 55, 45,  5, 89],
       [23, 46, 95, 74, 81, 44, 47, 77, 58, 84]])

# np.vstack:垂直级联
np.vstack((n1,n2))
# 执行结果
array([[12, 38, 49, 56, 52],
       [91, 43, 59, 18, 42],
       [23, 46, 95, 74, 81],
       [70, 42, 63, 86, 86],
       [73, 55, 45,  5, 89],
       [44, 47, 77, 58, 84]])
© 版权声明

相关文章

暂无评论

none
暂无评论...