gpt4 book ai didi

Python - 如何将嵌套字典加载到 Pandas 数据框中?

转载 作者:行者123 更新时间:2023-12-01 00:56:58 28 4
gpt4 key购买 nike

我有一个长嵌套字典,结构如下,我该如何将其加载到 Pandas 数据框中? FeedSpindle SpeedTool 的子键始终保持不变,但上面的两个级别(Heading) >、N1 等以及 40014002 等在整个词典中都是唯一的,或者至少在顺序上是唯一的。

我知道这样的事情:

pd.DataFrame.from_dict({(i,j): dictionary[i][j] 
for i in dictionary.keys()
for j in dictionary[i].keys()},
orient='index')

但这看起来像一个数据透视表,我更喜欢使用带有冗余信息的数据框(例如4001)来运行整个列。

{
"4001": {
"Heading": {
"Feed": [],
"Spindle Speed": [],
"Tool": []
},
"N1": {
"Feed": [],
"Spindle Speed": [],
"Tool": [
"0800"
]
},
"N10 ": {
"Feed": [
0.01,
0.0006,
0.0001,
0.0006,
0.0001,
0.0006,
0.0002,
0.02,
0.0004
],
"Spindle Speed": [
"M3S2630"
],
"Tool": [
"1616"
]
}
},
"4002": {
"Heading": {
"Feed": [],
"Spindle Speed": [],
"Tool": []
},
"N1": {
"Feed": [],
"Spindle Speed": [],
"Tool": [
"9900"
]
},
"N10": {
"Feed": [
0.01,
0.001,
0.0004,
0.001,
0.005
],
"Spindle Speed": [],
"Tool": [
"3838"
]
}
},
"4003": {...
...
...

理想情况下,数据框看起来像这样:

Program Operation Number    Feed        Tool      Spindle Speed
4001 Heading [] [] []
4001 N1 [] ['0800'] []
4001 N10 [0.01, ...] ['1616'] ['M3S2630']

最佳答案

你就快到了。您只需重置 multi_index 并给出正确的列名称:

pd.DataFrame.from_dict({(i,j): dictionary[i][j] 
for i in dictionary.keys()
for j in dictionary[i].keys()},
orient='index').reset_index().rename(
{'level_0': 'Program', 'level_1': 'Operation Number'}, axis=1)

关于Python - 如何将嵌套字典加载到 Pandas 数据框中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56170853/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com