Qubix
Qubix

Reputation: 4353

Dataframe to dictionary, by rows in pandas

I have a dataframe:

df = pd.DataFrame({'col1': [1, 2], 'col2': [0.5, 0.75]})

and I want to create the dict:

{1 : 0.5 , 2 : 0.75 }

I tried df.T.to_dict() but still does not work.

Upvotes: 1

Views: 50

Answers (2)

Dani Mesejo
Dani Mesejo

Reputation: 61920

As simple as zipping the columns together:

result = dict(zip(df.col1, df.col2))
print(result)

Or as an alternative:

result = dict(df[['col1', 'col2']].values)
print(result)

Upvotes: 0

jezrael
jezrael

Reputation: 863256

Create Series and convert to dictionary:

print (df.set_index('col1')['col2'].to_dict())
{1: 0.5, 2: 0.75}

Or use zip with dict:

print (dict(zip(df['col1'], ['col2'])))
{1: 0.5, 2: 0.75}

Upvotes: 1

Related Questions