Reputation: 2495
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 ?
Upvotes: 12
Views: 1246
Reputation: 71560
Or use dict(zip(...))
:
>>> cols = ["Length","Width","Height","Pid"]
>>> items_dic = dict(zip(df['Pid'],df[cols].values.tolist()))
>>> items_dic
{20: [4.8, 4.3, 4.3, 20.0], 21: [4.8, 4.3, 4.3, 21.0], 22: [6.0, 5.6, 9.0, 22.0], 23: [8.75, 5.6, 6.6, 23.0], 24: [6.0, 5.16, 6.6, 24.0]}
>>>
Upvotes: 7
Reputation: 862481
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]}
Upvotes: 13