panda dataframe to ordered dictionary

后端 未结 1 336
再見小時候
再見小時候 2020-12-17 03:15

There is a post in which a panda dataframe is converted in to a dictionary for further processing.

The code to do this is:

df = pd.read_excel(open(         


        
相关标签:
1条回答
  • 2020-12-17 04:09

    You can get the dictionary in the desired order by using an OrderedDict with keys from the Unique_id column. The following should serve as an illustration:

    from collections import OrderedDict
    
    # Get the unordered dictionary
    unordered_dict = df.set_index('Unique_id').T.to_dict('list')
    
     # Then order it
    ordered_dict = OrderedDict((k,unordered_dict.get(k)) for k in df.Unique_id)
    # OrderedDict([(1, [3, 4, 43, 90]), (2, [54, 6, 43, 54])])
    

    Thanks!

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