0

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')}

3 Answers 3

3

Lets try

df.agg(tuple,1).to_dict()
Sign up to request clarification or add additional context in comments.

Comments

1

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)))

Comments

1

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')}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.