Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Machine Learning by (11.4k points)

I have a Python dictionary like the following:

{u'2012-06-08': 388, 

 u'2012-06-09': 388,

 u'2012-06-10': 388,

 u'2012-06-11': 389,

 u'2012-06-12': 389,

 u'2012-06-13': 389,

 u'2012-06-14': 389}

The keys are Unicode dates and the values are integers. I would like to convert this into a pandas data frame by having the dates and their corresponding values as two separate columns. Example: col1: Dates col2: DateValue (the dates are still Unicode and date values are still integers)

   Date Date Value 

0 2012-07-01 391 

1 2012-07-02 392 

2 2012-07-03 392 

3  2012-07-04 392

 .               …     ...

Any help in this direction would be much appreciated. I am unable to find resources on the pandas docs to help me with this.

I know one solution might be to convert each key-value pair in this dict, into a dict so the entire structure becomes a dict of dicts, and then we can add each row individually to the data frame. But I want to know if there is an easier way and a more direct way to do this.

So far I have tried converting the dict into a series object but this doesn't seem to maintain the relationship between the columns:

s = Series(my_dict,index=my_dict.keys())

1 Answer

0 votes
by (33.1k points)

You can simply use:

pandas.DataFrame.from_dict

This function takes a dictionary as input to convert into a data frame.

For Example:

>>> data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}

>>> pd.DataFrame.from_dict(data)

   col_1 col_2

0      3 a

1      2 b

2      1 c

3      0 d

Hope this answer helps.

Browse Categories

...