Convert Python dict into a dataframe

前端 未结 16 2396
暗喜
暗喜 2020-11-22 03:18

I have a Python dictionary like the following:

{u\'2012-06-08\': 388,
 u\'2012-06-09\': 388,
 u\'2012-06-10\': 388,
 u\'2012-06-11\': 389,
 u\'2012-06-12\':          


        
相关标签:
16条回答
  • 2020-11-22 03:59

    p.s. in particular, I've found Row-Oriented examples helpful; since often that how records are stored externally.

    https://pbpython.com/pandas-list-dict.html

    0 讨论(0)
  • 2020-11-22 03:59

    In my case I wanted keys and values of a dict to be columns and values of DataFrame. So the only thing that worked for me was:

    data = {'adjust_power': 'y', 'af_policy_r_submix_prio_adjust': '[null]', 'af_rf_info': '[null]', 'bat_ac': '3500', 'bat_capacity': '75'} 
    
    columns = list(data.keys())
    values = list(data.values())
    arr_len = len(values)
    
    pd.DataFrame(np.array(values, dtype=object).reshape(1, arr_len), columns=columns)
    
    0 讨论(0)
  • 2020-11-22 04:00

    This is how it worked for me :

    df= pd.DataFrame([d.keys(), d.values()]).T
    df.columns= ['keys', 'values']  # call them whatever you like
    

    I hope this helps

    0 讨论(0)
  • 2020-11-22 04:03

    As explained on another answer using pandas.DataFrame() directly here will not act as you think.

    What you can do is use pandas.DataFrame.from_dict with orient='index':

    In[7]: pandas.DataFrame.from_dict({u'2012-06-08': 388,
     u'2012-06-09': 388,
     u'2012-06-10': 388,
     u'2012-06-11': 389,
     u'2012-06-12': 389,
     .....
     u'2012-07-05': 392,
     u'2012-07-06': 392}, orient='index', columns=['foo'])
    Out[7]: 
                foo
    2012-06-08  388
    2012-06-09  388
    2012-06-10  388
    2012-06-11  389
    2012-06-12  389
    ........
    2012-07-05  392
    2012-07-06  392
    
    0 讨论(0)
  • 2020-11-22 04:05

    You can also just pass the keys and values of the dictionary to the new dataframe, like so:

    import pandas as pd
    
    myDict = {<the_dict_from_your_example>]
    df = pd.DataFrame()
    df['Date'] = myDict.keys()
    df['DateValue'] = myDict.values()
    
    0 讨论(0)
  • 2020-11-22 04:05

    I have run into this several times and have an example dictionary that I created from a function get_max_Path(), and it returns the sample dictionary:

    {2: 0.3097502930247044, 3: 0.4413177909384636, 4: 0.5197224051562838, 5: 0.5717654946470984, 6: 0.6063959031223476, 7: 0.6365209824708223, 8: 0.655918861281035, 9: 0.680844386645206}

    To convert this to a dataframe, I ran the following:

    df = pd.DataFrame.from_dict(get_max_path(2), orient = 'index').reset_index()

    Returns a simple two column dataframe with a separate index:

    index 0 0 2 0.309750 1 3 0.441318

    Just rename the columns using f.rename(columns={'index': 'Column1', 0: 'Column2'}, inplace=True)

    0 讨论(0)
提交回复
热议问题