Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'), sheetname="Sheet1")
dict = df.set_index('id').T.to_dict('dict')

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

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

Currently, I am using the dictionary generated from pandas and assign those values in to an Ordered Dictionary, one by one. This is not the optimum way, as the order is scrambled

Example input: An Excel file 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 like this:

{1:[3,4,43,90], 2:[54,6,43,54]}
like image 331
Pavlos Panteliadis Avatar asked Dec 05 '16 21:12

Pavlos Panteliadis


People also ask

How do I convert a Pandas DataFrame to a dictionary?

To convert pandas DataFrame to Dictionary object, use to_dict() method, this takes orient as dict by default which returns the DataFrame in format {column -> {index -> value}} . When no orient is specified, to_dict() returns in this format.

How do I convert a row into a DataFrame dictionary?

DataFrame to dict by row index When we have a DataFrame with row indexes and if we need to convert the data of each row from DataFrame to dict , we can use the index parameter of the DataFrame. to_dict() function. It returns a list of dictionary objects. A dict is created for each row.

How do you turn a series into a dictionary?

Use pandas Series. to_dict() function to convert Series to a dictionary (dict). If you want convert DataFrame to Dictionary use DataFrame.to. dict() function.

Is Pandas DataFrame a dictionary?

Pandas can create dataframes from many kinds of data structures—without you having to write lots of lengthy code. One of those data structures is a dictionary.


1 Answers

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!

like image 148
Abdou Avatar answered Sep 29 '22 07:09

Abdou