Reputation: 1189
I have a dictionary like this
{'community_0': 30,
'community_1': 29,
'community_2': 15,
'community_3': 16,
'community_4': 123,
'community_5': 9,
'community_6': 36,
'community_7': 71,
'community_8': 95,
'community_9': 21}
i want to convert it to a pandas dataframe. I tried pd.DataFrame.from_dict(dict, orient='index')
but it gave me something else:
I referred to this post Convert Python dict into a dataframe but it didn't help much.
Any suggestions would be appreciated.
Upvotes: 0
Views: 1317
Reputation: 421
It depends what type of structure you want in Dataframe.
If you want to show keys in dict as rows value, then use:
-> pd.DataFrame(pd.Series(d)).reset_index()
If you want to show keys in dict as columns, then follow below steps:
First use your dictionary in a "List" like this:
d = [ { 'community_0': 31, 'community_1': 29 'community_2': 15 } ]
Then use -> pd.DataFrame.from_dict(d)
Upvotes: 1
Reputation: 2905
It is possible to create a pd.Series
directly out of your dictionary, and then use the .to_frame()
method to turn a pd.Series
into a single-column DataFrame:
import pandas as pd
d = {'community_0': 30,
'community_1': 29,
'community_2': 15,
'community_3': 16,
'community_4': 123,
'community_5': 9,
'community_6': 36,
'community_7': 71,
'community_8': 95,
'community_9': 21}
pd.Series(d).to_frame()
returns:
0
community_0 30
community_1 29
community_2 15
community_3 16
community_4 123
community_5 9
community_6 36
community_7 71
community_8 95
community_9 21
Upvotes: 1