将字典字典转换为pandas数据框

时间:2015-08-24 04:39:53

标签: python pandas

我有以下嵌套词典:

In [3]: nested_dict
Out[3]:
{'2': {'lagtime': {'darkgreen': 210,
   'darkorange': 141,
   'pink': 142,
   'red': 141}}}

我想要做的是创建一个数据框

0  2   darkgreen  lagtime    210
1  2  darkorange  lagtime    141
2  2        pink  lagtime    142
3  2         red  lagtime    141

我尝试了但失败了:

import pandas as pd
pd.DataFrame.from_dict(nested_dict)

我得到了这个意想不到的输出:

Out[4]:
                                                         2
lagtime  {u'pink': 142, u'darkorange': 141, u'darkgreen...

做正确的方法是什么?

1 个答案:

答案 0 :(得分:2)

首先需要将嵌套字典转换为字典列表或列表字典,然后才能将其转换为DataFrame。示例(转换为词典列表) -

list_of_dict = []
for key, value in nested_dict.items():
    for key1, value1 in value.items():
        for key2,value2 in value1.items():
            list_of_dict.append({'A':key,'B':key1,'C':key2,'D':value2})

df = pd.DataFrame(list_of_dict)

使用正确的列名而不是'A''B'

示例/演示 -

In [2]: nested_dict = {'2': {'lagtime': {'darkgreen': 210,
   ...:    'darkorange': 141,
   ...:    'pink': 142,
   ...:    'red': 141}}}

In [4]: list_of_dict = []

In [7]: for key, value in nested_dict.items():
   ...:     for key1, value1 in value.items():
   ...:         for key2,value2 in value1.items():
   ...:             list_of_dict.append({'A':key,'B':key1,'C':key2,'D':value2})
   ...:

In [8]: df = pd.DataFrame(list_of_dict)

In [9]: df
Out[9]:
   A        B           C    D
0  2  lagtime   darkgreen  210
1  2  lagtime        pink  142
2  2  lagtime  darkorange  141
3  2  lagtime         red  141