Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Covert a Pandas Dataframe to Dictionary

I been trying this for the past hour but with little to no success

I was wondering how can I make this dataframe to a dictionary

DF

 Country      Continent 
 1            Europe
 2            Europe
 3            Asia
 4            Australia

Desired

  {'1': 'Europe',
  '2': 'Europe',
  '3': 'Asia',
  '5': 'Australia'}

I tired like x10 different variations of code similar to this but it didn't work

 df.set_index('Country', inplace=True)
 df = df.to_dict('dict')
like image 434
OptimusPrime Avatar asked Sep 18 '18 13:09

OptimusPrime


People also ask

How do I convert a pandas DataFrame to a dictionary?

To convert pandas DataFrame to Dictionary object, use to_dict() method, this takes orient as dict by default which returns the DataFrame in format {column -> {index -> value}} . When no orient is specified, to_dict() returns in this format.

Can I put a DataFrame in a dictionary Python?

A pandas DataFrame can be converted into a Python dictionary using the DataFrame instance method to_dict(). The output can be specified of various orientations using the parameter orient. In dictionary orientation, for each column of the DataFrame the column value is listed against the row label in a dictionary.

Is pandas DataFrame a dictionary?

Pandas can create dataframes from many kinds of data structures—without you having to write lots of lengthy code. One of those data structures is a dictionary.


1 Answers

You can select column Continent for Series and then use Series.to_dict:

>>> d = df.set_index('Country')['Continent'].to_dict()
>>> print(d)
{'Paris': 'Europe', 'Berlin': 'Europe', 'Macow': 'Asia', 'Melbourne': 'Australia'}
like image 195
jezrael Avatar answered Oct 04 '22 02:10

jezrael