Reputation: 651
I have a dataframe like this:
>>> df = pd.DataFrame(np.array([[1, 2], ['a', 'b']]), columns=['col1', 'col2'])
>>> df
col1 col2
0 1 2
1 a b
What I am trying to do is to create a dict from this dataframe where row index is the key and col1 and col2 are a value in a tuple form for my dict. Here is what I am doing but this returns a list:
>>> import numpy as np
>>> import pandas as pd
>>> df.T.to_dict('list')
{0: ['1', '2'], 1: ['a', 'b']}
Here is what I am trying to get:
{0: ('1', '2'), 1: ('a', 'b')}
Upvotes: 0
Views: 154
Reputation: 51335
Another way is to take the dict you have apply a dict comprehension:
>>> {k: tuple(v) for k, v in df.T.to_dict("list").items()}
{0: ('1', '2'), 1: ('a', 'b')}
Upvotes: 1
Reputation: 323226
Not sure about the speed but with itertuples
dict(zip(df.index, df.itertuples(index=False, name=None)))
{0: ('1', '2'), 1: ('a', 'b')}
Or
dict(zip(df.index,map(tuple,df.values)))
Upvotes: 1