Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Create dict where one column is key and list of remaining columns are values

Below is the df:

In [1114]: df
Out[1114]: 
   site_id   a  b  c   d    e
0        1   4  2  5  50  150
1        2  56  3  6  60  160
2        3   7  4  7  70  170
3        4   8  5  8  80  180

I want to create a dict where column site_id is key and list of other columns are as values.

My attempt:

In [1101]: y = df.site_id.values
In [1109]: x = df[df.columns.difference(['site_id'])].values

In [1112]: d = {i:x[c] for c,i in enumerate(y)}
In [1113]: d
Out[1113]: 
{1: array([  4,   2,   5,  50, 150]),
 2: array([ 56,   3,   6,  60, 160]),
 3: array([  7,   4,   7,  70, 170]),
 4: array([  8,   5,   8,  80, 180])}

I am able to solve it, but looking for a more pandaic way.

Expected output:

{1: [4, 2, 5, 50, 150],
 2: [56, 3, 6, 60, 160],
 3: [7, 4, 7, 70, 170],
 4: [8, 5, 8, 80, 180]}
like image 731
Mayank Porwal Avatar asked Feb 11 '21 06:02

Mayank Porwal


2 Answers

apply agg to df should send all column values to list. Setting site_id as index then makes it possible to dict resulting into a key: value pair

df.set_index('site_id').agg(list,1).to_dict()

{1: [4, 2, 5, 50, 150],
 2: [56, 3, 6, 60, 160],
 3: [7, 4, 7, 70, 170],
 4: [8, 5, 8, 80, 180]}
like image 88
wwnde Avatar answered Sep 27 '22 20:09

wwnde


Use DataFrame.to_dict with orient='list' and transpose DataFrame:

d = df.set_index('site_id').T.to_dict(orient='list')
print (d)
{1: [4, 2, 5, 50, 150],  
 2: [56, 3, 6, 60, 160], 
 3: [7, 4, 7, 70, 170], 
 4: [8, 5, 8, 80, 180]}
like image 20
jezrael Avatar answered Sep 27 '22 19:09

jezrael