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')
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.
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.
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.
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With