Covert a Pandas Dataframe to Dictionary
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')
Possible duplicate of python pandas dataframe to dictionary
– IanS
Sep 18 '18 at 13:12
2 Answers
2
You can select column Continent for Series and then use Series.to_dict:
Continent
Series
Series.to_dict
>>> d = df.set_index('Country')['Continent'].to_dict()
>>> print(d)
'Paris': 'Europe', 'Berlin': 'Europe', 'Macow': 'Asia', 'Melbourne': 'Australia'
You can use the dict constructor with zip
dict
zip
dict(zip(df.Country, df.Continent))
1: 'Europe', 2: 'Europe', 3: 'Asia', 4: 'Australia'
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Duplicate of python pandas dataframe to dictionary
– Zero
Sep 18 '18 at 13:10