Turning my dictionary into a pandas dataframe

后端 未结 4 1141
一生所求
一生所求 2021-01-19 23:01

I have a function which create several dicts of dicts, based on some conditions.

However, I would really like to turn the dict into a dataframe after collecting it.

4条回答
  •  有刺的猬
    2021-01-19 23:31

    You can flatten nested dictionaries 2 times for tuples for keys and pass to DataFrame.from_dict:

    d1 = {(k1, k2, k3): v3 
          for k1, v1 in d.items() 
          for k2, v2 in v1.items()
          for k3, v3 in v2.items()}
    
    df = pd.DataFrame.from_dict(d1, orient='index')
    #alternative
    #df = pd.DataFrame(d1).T
    

    print (df)
                       lowPrice   lowDate highPrice  highDate change
    TSLA 2011 negative   185.16  05/27/19    365.71  12/10/18  -0.49
         2012 negative   185.16  05/27/19    365.71  12/10/18  -0.49
         2013 negative    32.91  01/07/13     37.24  03/26/12  -0.12
              positive    32.91  01/07/13     190.9  09/23/13    4.8
    

提交回复
热议问题