字典到多索引的pandas数据帧

时间:2018-05-09 03:11:06

标签: python pandas dictionary

假设我有字典,

{('20170330', 'A'): {'earn': '16.02', 'lstdt': '2014/06/16', 'gap': '0.21','ocha': '5.44', 'nav': '77'},
('20170331', 'A'): {'earn': '25.68', 'lstdt': '2015/07/29','gap': '-1.41','ocha': '10.24', 'nav': '106'},
('20170331', 'B'): {'earn': '-', 'lstdt': '2016/09/12', 'gap':'-0.08', 'ocha': '0.79','nav': '145'}}

我怎样才能将其转换为类似于面板数据的多索引数据框?

估计结果是,

                     earn         lstdt     gap    ocha    nav
     date    name   
 20170330      A   16.02    2014/06/16    0.21    5.44     77
 20170331      A   25.68    2015/07/29   -1.41   10.24    106
               B   -        2016/09/12   -0.08    0.79    145

1 个答案:

答案 0 :(得分:1)

您可以使用from_dict(d, orient="index")

d = {...}
pd.DataFrame.from_dict(d, orient="index").rename_axis(["date", "name"])

结果:

                earn       lstdt    gap   ocha  nav
date     name                                      
20170330 A     16.02  2014/06/16   0.21   5.44   77
20170331 A     25.68  2015/07/29  -1.41  10.24  106
         B         -  2016/09/12  -0.08   0.79  145