converting a 2d dictionary to a numpy matrix

后端 未结 3 918
庸人自扰
庸人自扰 2020-12-24 14:00

I have a huge dictionary something like this:

d[id1][id2] = value

example:

books[\"auth1\"][\"humor\"] = 20
books[\"auth1\"         


        
3条回答
  •  [愿得一人]
    2020-12-24 14:14

    pandas do this very well:

    books = {}
    books["auth1"] = {}
    books["auth2"] = {}
    books["auth1"]["humor"] = 20
    books["auth1"]["action"] = 30
    books["auth2"]["comedy"] = 20
    
    from pandas import *
    
    df = DataFrame(books).T.fillna(0)
    

    The output is:

           action  comedy  humor
    auth1      30       0     20
    auth2       0      20      0
    

提交回复
热议问题