如何在Python中将含numpy数组的列表转换为一维object数组?
将包含numpy数组的列表转为一维object类型数组
问题说明
你有一个包含多个形状一致的numpy数组的列表:
import numpy as np # 示例输入列表 boxs = [ np.array([1145, 330, 1205, 364], dtype=np.int64), np.array([1213, 330, 1247, 364], dtype=np.int64), np.array([ 883, 377, 1025, 412], dtype=np.int64), np.array([1038, 377, 1071, 404], dtype=np.int64), np.array([1085, 377, 1195, 405], dtype=np.int64), np.array([1210, 377, 1234, 405], dtype=np.int64) ]
期望得到元素为子数组的一维object类型数组:
array([array([1145, 330, 1205, 364], dtype=int64), array([1213, 330, 1247, 364], dtype=int64), array([883, 377, 1025, 412], dtype=int64), array([1038, 377, 1071, 404], dtype=int64), array([1085, 377, 1195, 405], dtype=int64), array([1210, 377, 1234, 405], dtype=int64)], dtype=object)
但直接使用np.array(art)会生成二维数组,不符合需求。
问题原因
当列表中所有子数组形状一致时,numpy会自动将它们堆叠成多维数组,而非保留每个子数组作为独立的对象元素。
解决方案
方法1:显式指定dtype=object
创建数组时明确指定类型为object,阻止numpy自动堆叠:
art = [] for i in boxs: art.append(np.array(i, dtype=np.int64)) # 关键:指定dtype=object new_ary = np.array(art, dtype=object)
方法2:初始化空object数组再填充
若需要更灵活的控制,可先创建空的一维object数组,再逐个填入子数组:
art = [] for i in boxs: art.append(np.array(i, dtype=np.int64)) # 初始化长度为列表长度的一维object数组 new_ary = np.empty(len(art), dtype=object) # 逐个填充子数组 for idx, sub_arr in enumerate(art): new_ary[idx] = sub_arr
验证结果
执行后可通过以下命令确认结果符合要求:
print(new_ary.dtype) # 输出:object print(new_ary.shape) # 输出:(6,)
内容的提问来源于stack exchange,提问作者Laxmi
相关产品推荐
相关产品推荐

