Panda dataframe for ordered dictionary

There is a message in which the panda framework is converted to a dictionary for further processing.

Code for this:

df = pd.read_excel(open('data/file.xlsx', 'rb'), sheetname="Sheet1") dict = df.set_index('id').T.to_dict('dict') 

which gives something like this: {column -> {index -> value}}

Is there a quick way instead of {column -> {index -> value}} to get this: OrderedDict(column, value) as the return value?

I am currently using a dictionary generated from pandas and assigning these values ​​in an ordered dictionary one by one. This is not the best way, since the order is scrambled.

Input Example: An Excel file looks like this:

 Unique_id | column1 | column2 | column3 | column 4 1 | 3 | 4 | 43 | 90 2 | 54 | 6 | 43 | 54 

and the output should be an ordered dictionary as follows:

 {1:[3,4,43,90], 2:[54,6,43,54]} 
+5
source share
1 answer

You can get the dictionary in the desired order using OrderedDict with the keys from the Unique_id column. The following should illustrate:

 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!

+4
source

Source: https://habr.com/ru/post/1260834/


All Articles