python - 在 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
,在我的情况下,这两个值都没有帮助。因为它适用于平面词典。
我真的不知道如何处理这个问题。可能需要什么简单的库等等。
如果我可以澄清更多细节/细微差别,请告诉我。
解决方案
利用:
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
推荐阅读
- python-3.x - 在python中计算字典的值,其中值是集合
- stata - 如何在Stata中获得利润
- reactjs - 如何在reactjs中“通过单击警报框确定按钮隐藏div”
- amazon-web-services - 负载均衡器无法在 Elastic Beanstalk 中从 HTTP 重定向到 HTTPS
- c# - c# winforms根据带属性的字段动态创建控件(Attributes关键字)
- jquery - 我创建的 jquery div 没有出来,我做错了吗?C#
- reactjs - 减速器中的错误。初始状态。我如何初始化状态和使用 action.type
- python - Python Granger因果关系F检验理解
- stimulsoft - 通过在 Stimulusoft 中禁用缓存导致“未指定报告”错误
- r - 嵌套数据框的几个数据框的全连接