Skip to content Skip to sidebar Skip to footer

Panda Dataframe To Ordered Dictionary

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('data/file.xlsx', 'rb'), sheetn

Solution 1:

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!


Post a Comment for "Panda Dataframe To Ordered Dictionary"