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')}
Lets try
df.agg(tuple,1).to_dict()
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')}
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)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.