Hannah Lee
Hannah Lee

Reputation: 393

dictionary to multi-index pandas dataframe

Suppose I have dictionary looking like,

{('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'}}

How could I make this to multi-index dataframe which resembles panel data?

Estimated outcome being,

                     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

Upvotes: 5

Views: 4622

Answers (1)

HYRY
HYRY

Reputation: 97261

You can use from_dict(d, orient="index")

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

the result:

                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

Upvotes: 7

Related Questions