如何用纯Numpy解析含单个np.array的字典列表(替代Pandas)
纯Numpy实现字典列表的键值合并与数组堆叠
原始数据
import numpy as np listOfDicts = [{'key1': np.array(10), 'key2': np.array(10), 'key3': np.array(44)}, {'key1': np.array(2), 'key2': np.array(15), 'key3': np.array(22)}, {'key1': np.array(25), 'key2': np.array(25), 'key3': np.array(11)}, {'key1': np.array(35), 'key2': np.array(55), 'key3': np.array(22)}]
步骤1:转换为目标中间字典结构
通过字典推导式遍历所有键,收集每个键对应的单个元素数组值,合并为完整numpy数组后封装在列表中:
merged_dict = { key: [np.array([d[key].item() for d in listOfDicts])] for key in listOfDicts[0].keys() } # 输出验证 print(merged_dict) # {'key1': [array([10, 2, 25, 35])], # 'key2': [array([10, 15, 25, 55])], # 'key3': [array([44, 22, 11, 22])]}
步骤2:完成最终数组堆叠
从中间字典中排除key1,提取对应数组并沿轴1堆叠:
result = np.stack([merged_dict[key][0] for key in merged_dict if key != 'key1'], axis=1) # 输出结果 print(result) # array([[10, 44], # [15, 22], # [25, 11], # [55, 22]])
内容的提问来源于stack exchange,提问作者John Stud
相关产品推荐
相关产品推荐

