将嵌套字典转换为数据帧

时间:2014-03-31 01:51:00

标签: python dictionary pandas dataframe

我的字典看起来像这样

mydict = 
{240594.0: {1322.0: 1.6899999999999999, 1323.0: 1.6900000000000002, 1324.0: 1.6899999999999999, 1325.0: 1.6899999999999999, 1326.0: 1.6899999999999999, 1327.0: 1.6900000000000002, 1328.0: 1.6899999999999999, 1329.0: 1.6899999999999999, 1356.0: 1.6900000000000002, 1357.0: 1.6900000000000002, 1358.0: 1.6899999999999999, 1359.0: 1.6900000000000002, 1360.0: 1.6900000000000002, ...},

226918.0: {1322.0: 1.6900000000000002, 1323.0: 1.6899999999999999, 1324.0: 1.6900000000000002, 1325.0: 1.6899999999999999, 1326.0: 1.6900000000000002, 1327.0: 1.6899999999999999, 1328.0: 1.6900000000000002, 1329.0: 1.6899999999999999, 1352.0: 1.6900000000000002, 1353.0: 1.6900000000000002, 1354.0: 1.6899999999999999 ...}}

这是{iri_key: {week:price, week:price ...}, iri_key: {...}}的真正价值 我想将这个字典转换成看起来像

的数据框
         week week  week ...
irikey: price price price ...
irikey: ...    ...   ...

在上面的案例中

           1322.0                  ...
240594.0   1.6899999999999999      ...
226918.0   1.6900000000000002      ...

我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

您可能已经发现,DataFrame(mydict)是有效的代码。你可以简单地使用转置(.T)来获得你想要的结果。

在代码可读性和直接性方面,有一种更好的方法:使用特定的DataFrame构造函数DataFrame.from_dict,它具有关键字参数orient

In [2]: DataFrame.from_dict(mydict, orient='index')
Out[2]: 
        1356  1357  1358  1359  1360  1322  1323  1324  1325  1326  1327  \
226918   NaN   NaN   NaN   NaN   NaN  1.69  1.69  1.69  1.69  1.69  1.69   
240594  1.69  1.69  1.69  1.69  1.69  1.69  1.69  1.69  1.69  1.69  1.69   

        1328  1329  1352  1353  1354  
226918  1.69  1.69  1.69  1.69  1.69  
240594  1.69  1.69   NaN   NaN   NaN  

[2 rows x 16 columns]

从您提供的示例数据中可以看出,正确处理缺失值和变量长度。