如何在不扁平化的情况下将不等长数组添加到NumPy数组中
如何用NumPy构建包含不等长子数组的嵌套数组结构
当你尝试直接将长度不同的NumPy数组组合成嵌套结构时,np.array([a,b,c,d])会因为数组形状不均报错,而np.hstack会把所有元素扁平化,无法保留嵌套结构。要实现你预期的嵌套数组,可通过以下方法:
方法1:创建Object类型的NumPy数组
NumPy的object类型数组允许存储不同长度的子数组,本质是把每个子数组作为独立对象存入容器数组中。
单层级嵌套示例
import numpy as np a = np.array([112,123,134,145]) b = np.array([212,223,234]) c = np.array([312,323]) d = np.array([412]) # 初始化一个指定长度的object类型数组 nested_arr = np.empty(4, dtype=object) # 逐个赋值子数组 nested_arr[0] = a nested_arr[1] = b nested_arr[2] = c nested_arr[3] = d print(nested_arr)
输出结果:
array([array([112, 123, 134, 145]), array([212, 223, 234]), array([312, 323]), array([412])], dtype=object)
多层级嵌套示例
如果要构建你预期的两层嵌套结构,只需将多个单层级嵌套数组再组合成一个更大的object数组:
# 构建第二组子数组 a2 = np.array([512,523,534,545]) b2 = np.array([612,623,634]) c2 = np.array([712,723]) d2 = np.array([812]) # 生成第二个单层级嵌套数组 nested_arr2 = np.empty(4, dtype=object) nested_arr2[0] = a2 nested_arr2[1] = b2 nested_arr2[2] = c2 nested_arr2[3] = d2 # 组合成两层嵌套数组 final_arr = np.array([nested_arr, nested_arr2], dtype=object) print(final_arr)
输出结果:
array([array([array([112, 123, 134, 145]), array([212, 223, 234]), array([312, 323]), array([412])], dtype=object), array([array([512, 523, 534, 545]), array([612, 623, 634]), array([712, 723]), array([812])], dtype=object)], dtype=object)
方法2:列表转Object数组
也可以先将子数组存入普通列表,再直接转为object类型的NumPy数组,写法更简洁:
nested_list = [a, b, c, d] nested_arr = np.array(nested_list, dtype=object)
效果和方法1完全一致。
注意事项
- object类型数组更像是"容器",它不支持普通NumPy数组的矢量化运算(比如直接对整个数组做加减乘除),因为每个元素是独立的子数组。
- 如果需要频繁进行数值计算,嵌套列表可能比object数组更灵活;但如果必须用NumPy数组作为容器,上述方法是最优解。
内容的提问来源于stack exchange,提问作者Majoris
相关产品推荐
相关产品推荐

