【发布时间】:2020-10-14 18:51:19
【问题描述】:
我有什么:
如下形式的嵌套字典a
a={
"level1": {
"t1":{
"s1":{
"col1":5,
"col2":4,
"col3":4,
"col4":9
},
"s2":{
"col1":1,
"col2":5,
"col3":4,
"col4":8
},
"s3":{
"col1":11,
"col2":8,
"col3":2,
"col4":9
},
"s4":{
"col1":5,
"col2":4,
"col3":4,
"col4":9
}
},
"t2":{
"s1":{
"col1":5,
"col2":4,
"col3":4,
"col4":9
},
"s2":{
"col1":1,
"col2":5,
"col3":4,
"col4":8
},
"s3":{
"col1":11,
"col2":8,
"col3":2,
"col4":9
},
"s4":{
"col1":5,
"col2":4,
"col3":4,
"col4":9
}
},
"t3":{
"s1":{
"col1":1,
"col2":2,
"col3":3,
"col4":4
},
"s2":{
"col1":5,
"col2":6,
"col3":7,
"col4":8
},
"s3":{
"col1":9,
"col2":10,
"col3":11,
"col4":12
},
"s4":{
"col1":13,
"col2":14,
"col3":15,
"col4":16
}
}
},
"level2": {
"t1":{
"s1":{
"col1":5,
"col2":4,
"col3":9,
"col4":9
},
"s2":{
"col1":1,
"col2":5,
"col3":4,
"col4":5
},
"s3":{
"col1":11,
"col2":8,
"col3":2,
"col4":13
},
"s4":{
"col1":5,
"col2":4,
"col3":4,
"col4":20
}
},
"t2":{
"s1":{
"col1":5,
"col2":4,
"col3":4,
"col4":9
},
"s2":{
"col1":1,
"col2":5,
"col3":4,
"col4":8
},
"s3":{
"col1":11,
"col2":8,
"col3":2,
"col4":9
},
"s4":{
"col1":5,
"col2":4,
"col3":4,
"col4":9
}
},
"t3":{
"s1":{
"col1":1,
"col2":2,
"col3":3,
"col4":4
},
"s2":{
"col1":5,
"col2":6,
"col3":7,
"col4":8
},
"s3":{
"col1":9,
"col2":10,
"col3":11,
"col4":12
},
"s4":{
"col1":13,
"col2":14,
"col3":15,
"col4":16
}
}
}
}
即标记为"level"的键是a的主键,标记为"t"的键是每个"level"中嵌套字典的键,最后标记为"s"的键。现在,对应于每个标记为 "s" 的键,有一个字典,其中包含四个键 "col1","col2", "col3" 和 "col4" 实际数据所在的位置。
目标:
我想通过以下方式从a 构造一个熊猫数据框:
Nested Dictionary into the dataframe
也就是说,我希望 "level" 和 "t" 键分别用作数据帧的主索引和辅助索引,而 "s" 和 "col" 键分别用作此的主列和辅助列数据框。
到目前为止我尝试过的方法:
我尝试使用pandas.DataFrame.from_dict 和pandas.json_normalize 方法。已经有一个类似问题的解决方案,它使用pandas.DataFrame.from_dict,但我没有从中得到太多帮助,因为它使用a 中的"s" 键作为索引而不是数据框中的主列,并且我无法理解 pandas.json_normalize 的工作原理,因此无法获得预期的结果
pandas 有什么函数可以直接实现吗?另外,我不知道 pandas 数据框是否支持这种类型的列。
我在 Python 3.8.3 上使用 pandas 版本 1.0.5。任何帮助表示赞赏。提前谢谢你
【问题讨论】:
标签: python-3.x pandas dataframe dictionary