Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dataframe into dictionary

I have a dataframe and i want it to select a few columns and convert it into Dictionary in the a certain manner

Dataframe:

Dataframe :

and here's the output I want

{20: [4.6, 4.3, 4.3, 20],
21: [4.6, 4.3, 4.3, 21],
 22: [6.0, 5.6, 9.0, 22],
 23: [8.75, 5.6, 6.6, 23]}

I have tried this

items_dic = data[["Length","Width","Height","Pid" ]].set_index('Pid').T.to_dict('list')

items_dic = {20: [4.6, 4.3, 4.3],
 21: [4.6, 4.3, 4.3],
 22: [6.0, 5.6, 9.0],
 23: [8.75, 5.6, 6.6]}

but this does not include Pid in the list of values Can someone explain why ?

like image 763
Rahul Sharma Avatar asked Mar 12 '19 06:03

Rahul Sharma


People also ask

How do you convert a 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.

Can we convert DataFrame to dictionary in Python?

A pandas DataFrame can be converted into a Python dictionary using the DataFrame instance method to_dict(). The output can be specified of various orientations using the parameter orient. In dictionary orientation, for each column of the DataFrame the column value is listed against the row label in a dictionary.

How do you create a data dictionary from a DataFrame in Python?

Method 1: Create DataFrame from Dictionary using default Constructor of pandas. Dataframe class. Method 2: Create DataFrame from Dictionary with user-defined indexes. Method 3: Create DataFrame from simple dictionary i.e dictionary with key and simple value like integer or string value.

How do you create a dictionary from a DataFrame column?

You can use df. to_dict() in order to convert the DataFrame to a dictionary.


1 Answers

Set parameter drop=False in DataFrame.set_index, because default parameter drop=False move column to index:

cols = ["Length","Width","Height","Pid"]
items_dic = data[cols].set_index('Pid', drop=False).T.to_dict('list')

print (items_dic)

{20: [4.6, 4.3, 4.3, 20.0], 
 21: [4.6, 4.3, 4.3, 21.0], 
 22: [6.0, 5.6, 9.0, 22.0], 
 23: [8.75, 5.6, 6.6, 23.0]}
like image 123
jezrael Avatar answered Sep 30 '22 10:09

jezrael