How can I transform a pandas dataframe into a dictionary without the column headers?

Eva :

My current df:


   header1    header2  
   Siam       Thailand      
   Indonesie  Indonesia       
   Arabie     Yemen       
   Ceylon     Sri Lanka      

So the headers of my df are 'header1' and 'header2'. The values are everything under these two headers.

I would like to transform this df into a flat dictionary, where the dictionary keys are the values of header1 and the dictionary values are the values of header2, like so:

Desired output:

{'Siam': 'Thailand', 'Indonesië': 'Indonesia', 'Arabië': 'Yemen', 'Ceylon': 'Sri Lanka'}

Current output:

{'header2':{'Siam': 'Thailand', 'Indonesie': 'Indonesia', 'Arabie': 'Yemen', 'Ceylon': 'Sri Lanka'}}

My code:

df.to_dict()
Quang Hoang :

This is just:

{a:b for a,b in zip(df['header1'], df['header2'])}

or if you insist on pandas solution:

df.set_index('header1')['header2'].to_dict()

Output:

{'Siam': 'Thailand',
 'Indonesie': 'Indonesia',
 'Arabie': 'Yemen',
 'Ceylon': 'Sri Lanka'}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=345990&siteId=1