I have a dataframe and i want it to select a few columns and convert it into Dictionary in the a certain manner
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 ?
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.
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.
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.
You can use df. to_dict() in order to convert the DataFrame to a dictionary.
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]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With