我有一个结构如下的长嵌套字典,如何将其加载到Pandas数据框中? FeedSpindle SpeedTool的子键始终保持相同,但上方的两个级别(HeadingN1等以及40014002等)是唯一的或至少在整个字典中以独特的顺序排列。

我知道这样的事情:

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


但这看起来像一个数据透视表,在这里,我更喜欢一个带有冗余信息的数据框(liek 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)

07-24 09:52
查看更多