create pandas dataframe from dictionary of dictionaries

后端 未结 2 1920
醉梦人生
醉梦人生 2020-12-13 12:32

I have a dictionary of dictionaries of the form:

{\'user\':{movie:rating} }

For example,

{Jill\': {\'Avenger: Age of Ultro         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 12:56

    You can pass the dict of dict to the DataFrame constructor:

    In [11]: d = {'Jill': {'Django Unchained': 6.5, 'Gone Girl': 9.0, 'Kill the Messenger': 8.0, 'Avenger: Age of Ultron': 7.0}, 'Toby': {'Django Unchained': 9.0, 'Zoolander': 2.0, 'Avenger: Age of Ultron': 8.5}}
    
    In [12]: pd.DataFrame(d)
    Out[12]:
                            Jill  Toby
    Avenger: Age of Ultron   7.0   8.5
    Django Unchained         6.5   9.0
    Gone Girl                9.0   NaN
    Kill the Messenger       8.0   NaN
    Zoolander                NaN   2.0
    

    Or use the from_dict method:

    In [13]: pd.DataFrame.from_dict(d)
    Out[13]:
                            Jill  Toby
    Avenger: Age of Ultron   7.0   8.5
    Django Unchained         6.5   9.0
    Gone Girl                9.0   NaN
    Kill the Messenger       8.0   NaN
    Zoolander                NaN   2.0
    
    In [14]: pd.DataFrame.from_dict(d, orient='index')
    Out[14]:
          Django Unchained  Gone Girl  Kill the Messenger  Avenger: Age of Ultron  Zoolander
    Jill               6.5          9                   8                     7.0        NaN
    Toby               9.0        NaN                 NaN                     8.5          2
    

提交回复
热议问题