如何将形状(1,2)的NumPy数组追加到(1,2,2)数组得到(1,3,2)?
NumPy数组追加实现指定形状结果
先看现有两个数组的定义和形状:
import numpy as np # 定义数组A A = [[2 , 3]] A = np.array(A) print("A的形状:", A.shape) # 输出 (1, 2) print("A:", A) # 输出 array([[2, 3]]) # 定义数组B B = [[[5, 7], [4, 8]]] B = np.array(B) print("B的形状:", B.shape) # 输出 (1, 2, 2) print("B:", B) # 输出 array([[[5, 7], # [4, 8]]])
需求:将数组A追加到数组B中,得到形状为(1, 3, 2)的数组,具体形式如下:
array([[[5, 7], [4, 8], [2, 3]]])
实现方法
因为A的形状是(1,2),而B的形状是(1,2,2),两者维度不匹配,无法直接拼接。需要先将A的形状调整为(1,1,2),和B在拼接维度上对齐,再沿**第1个轴(axis=1)**进行拼接:
# 扩展A的维度,将形状从(1,2)变为(1,1,2) A_expanded = np.expand_dims(A, axis=1) # 或者用reshape:A_expanded = A.reshape(1,1,2) # 沿axis=1拼接B和扩展后的A result = np.concatenate([B, A_expanded], axis=1) print("结果形状:", result.shape) # 输出 (1, 3, 2) print("结果:", result) # 输出 array([[[5, 7], # [4, 8], # [2, 3]]])
补充说明
- 使用
np.expand_dims可以精准地在指定位置增加维度,避免手动计算reshape参数出错; np.concatenate是NumPy中拼接数组的高效方法,相比np.append更灵活,推荐用于多维度数组的拼接操作;- 拼接时必须保证除了指定的拼接轴外,其他维度的大小完全一致,否则会报错。
内容的提问来源于stack exchange,提问作者prgtttt
相关产品推荐
相关产品推荐

