Pandas: create named columns in DataFrame from dict

anonuser0428 picture anonuser0428 · Dec 3, 2013 · Viewed 46.5k times · Source

I have a dictionary object of the form:

my_dict = {id1: val1, id2: val2, id3: val3, ...}

I want to create this into a DataFrame where I want to name the 2 columns 'business_id' and 'business_code'.

I tried:

business_df = DataFrame.from_dict(my_dict,orient='index',columns=['business_id','business_code'])

But it says from_dict doesn't take in a columns argument.

TypeError: from_dict() got an unexpected keyword argument 'columns'

Answer

Andy Hayden picture Andy Hayden · Dec 3, 2013

You can iterate through the items:

In [11]: pd.DataFrame(list(my_dict.iteritems()),
                      columns=['business_id','business_code'])
Out[11]: 
  business_id business_code
0         id2          val2
1         id3          val3
2         id1          val1