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]}
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]}
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]}
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