解决嵌套列表转NumPy数组形状问题:将(a,1,c)转(a,)
解决方案
1. 单个(a,1,c)数组转(a,)的方法
手动遍历赋值
直接创建空的object类型数组,将(a,1,c)数组中每个位置的[0,:]子数组赋值进去:
import numpy as np # 示例:形状为(2,1,3)的数组 arr = np.array([[[1,2,3]], [[5,4,7]]]) # 创建形状为(2,)的object数组 converted_arr = np.empty(arr.shape[0], dtype=object) for i in range(arr.shape[0]): converted_arr[i] = arr[i, 0, :] print(converted_arr.shape) # 输出 (2,) print(converted_arr[0]) # 输出 [1 2 3]
列表推导式简化
用列表推导式提取子元素后,再转为object数组:
arr = np.array([[[1,2,3]], [[5,4,7]]]) converted_arr = np.array([sub[0] for sub in arr], dtype=object) print(converted_arr.shape) # 输出 (2,)
2. 整合到outer_list的完整处理流程
针对你的嵌套列表,先统一处理所有内部数组,确保它们都转为(a,)形状的object数组,再组合成外层数组并保存:
import numpy as np outer_list = [ [ [[1, 2, 3], [4, 6, 7]], [[7, 8, 9], [11, 15, 17]] ], [ [[5, 6, 7], [3, 4, 6], [1, 2, 4]], [[1, 6, 3], [3, 6, 4], [34, 2, 1]] ], [ [[1, 2, 3]], [[5, 4, 7]] ] ] processed_outer = [] for inner_list in outer_list: processed_inner = [] for sub_list in inner_list: arr = np.array(sub_list) # 判断是否为需要转换的(a,1,c)形状 if arr.ndim == 3 and arr.shape[1] == 1: converted = np.array([x[0] for x in arr], dtype=object) else: converted = np.array(sub_list, dtype=object) processed_inner.append(converted) processed_outer.append(np.array(processed_inner, dtype=object)) # 生成最终可保存的数组 final_arr = np.array(processed_outer, dtype=object) # 保存为.npy文件 np.save("output.npy", final_arr)
内容的提问来源于stack exchange,提问作者Mistakamikaze
相关产品推荐
相关产品推荐

