python - 从嵌套字典构造熊猫多索引数据框
问题描述
我想在这里从嵌套字典构建熊猫数据框:
res = {'loss': {'first_neuron': {10: 0.6430850658151839,
12: 0.6419735709090292,
14: 0.628668905776224},
'lr': {0.001: 0.7243950462635652,
0.01: 0.6431898441579607,
0.1: 0.5461426520789111}},
'accuracy': {'first_neuron': {10: 0.6125457246362427,
12: 0.6154635353588763,
14: 0.6285751049901233},
'lr': {0.001: 0.5127914948963824,
0.01: 0.6298153875050722,
0.1: 0.7139774825837877}}}
对此:
解决方案
您的 dict 包含许多嵌套级别,它们与 pandas 不相配。您可以先将 dict 解析为更简单的 dict,然后稍微操作数据框:
from collections import defaultdict
tmp = defaultdict(list)
for key1, value1 in res.items():
for key2, value2 in value1.items():
for key3, value3 in value2.items():
tmp['metric'].append(key1)
tmp['index1'].append(key2)
tmp['index2'].append(key3)
tmp['value'].append(value3)
df = (
pd.DataFrame(tmp)
.pivot(index=['index1', 'index2'], columns='metric')
.droplevel(0, axis=1)
.rename_axis(columns=None)
)
结果:
accuracy loss
index1 index2
first_neuron 10.000 0.612546 0.643085
12.000 0.615464 0.641974
14.000 0.628575 0.628669
lr 0.001 0.512791 0.724395
0.010 0.629815 0.643190
0.100 0.713977 0.546143
推荐阅读
- android - 所有软件包均不提供下载!以下软件包不可用: - 软件包 id 模拟器我正在尝试运行我的虚拟设备,
- python - 通过路径获取树的元素
- javascript - 如何将 json 值附加到文件外的数组中
- python - 显示序列化程序中不存在模型的数据 - Python - Django - Django Rest Framework
- pytorch - 创建一个具有 1xD 内核的 CNN,其中 D 是在 MxD 矩阵上垂直滑动的列数?
- sympy - 从 Sympy 表达式中消除不必要的分段项
- java - SingleOutputStreamOperator#returns(TypeHint 的 javadoc
typeHint) 方法 - python - 使用python从包含基于不同类别的文件夹的单个图像创建子文件夹
- javascript - TypeScript + Vue 3 - ReferenceError:未定义变量
- python - 彩条限制不符合数据限制