首页 > 解决方案 > 在 Python 中将字典转换为 DataFrame

问题描述

我有一个静态结构的字典:

Key: Key: Value`

我需要将数据记录一些额外的键,深度相同,所以有点统一。

示例字典:

{
    "Emissions": {
        "305-1": [
            "2014_249989",
            "2015_339998",
            "2016_617957",
            "2017_827230"
        ],
        "305-2": [
            "2014_33163",
            "2015_64280",
            "2016_502748",
            "2017_675091"
        ],
    },
    "Effluents and Waste": {
        "306-1": [
            "2014_143.29",
            "2015_277.86",
            "2016_385.67",
            "2017_460.6"
        ],
        "306-2": "blah blah blah",
    }
}

我想要一个这种结构的DataFrame:

Parent Key | Child Key | Child Value
Parent Key | Child Key | Child Value
Parent Key | Child Key | Child Value
Parent Key | Child Key | Child Value

示例所需的数据帧:

Emissions | 305-1 | ["2014_249989", "2015_339998", "2016_617957", "2017_827230"]
Emissions | 305-2 | ["2014_33163", "2015_64280", "2016_502748", "2017_675091"]
Effluents and Waste| 306-1 | ["2014_249989", "2015_339998", "2016_617957", "2017_827230"]
Effluents and Waste | 306-2 | blah blah blah

其中所有子值都是字符串的列表对象或字符串对象。


通过研究,我发现pandas.DataFrame.from_dict()。但是orient,在我的情况下,这两个值都没有帮助。因为它适用于平面词典。

我真的不知道如何处理这个问题。可能需要什么简单的库等等。

如果我可以澄清更多细节/细微差别,请告诉我。

标签: pythonpandasdataframedictionary

解决方案


利用:

import pandas as pd

data = {
    "Emissions": {
        "305-1": ["2014_249989", "2015_339998", "2016_617957", "2017_827230"],
        "305-2": ["2014_33163", "2015_64280", "2016_502748", "2017_675091"],
    },
    "Effluents and Waste": {
        "306-1": ["2014_143.29", "2015_277.86", "2016_385.67", "2017_460.6"],
        "306-2": "blah blah blah",
    }
}

data = [[key, ikey, value] for key, values in data.items() for ikey, value in values.items()]
res = pd.DataFrame(data)
print(res)

输出

                     0  ...                                                  2
0            Emissions  ...  [2014_249989, 2015_339998, 2016_617957, 2017_8...
1            Emissions  ...  [2014_33163, 2015_64280, 2016_502748, 2017_675...
2  Effluents and Waste  ...  [2014_143.29, 2015_277.86, 2016_385.67, 2017_4...
3  Effluents and Waste  ...                                     blah blah blah

推荐阅读