Pandas: create named columns in DataFrame from dict

51,980

Solution 1

You can iterate through the items:

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

Solution 2

To get the same functionality as the documentation and avoid using code workarounds, make sure you're using the most recent version of Pandas. I recently encountered the same error when running a line of code from the Pandas tutorial:

pd.DataFrame.from_dict(dict([('A', [1, 2, 3]), ('B', [4, 5, 6])]),orient='index', columns=['one', 'two', 'three'])

I checked the version of Pandas and found I was running version 22, when version 23 is available.

import pandas as pd
pd.__version__
Out[600]: '0.22.0'

I upgraded using pip:

c:\pip install --upgrade pandas

I confirmed my version updated to 23, and the same from_dict() code worked without error. No code modifications required.

Solution 3

From version 0.23.0, you can specify a columns parameter in from_dict:

my_dict = {id1: val1, id2: val2, id3: val3, ...}
prepared_dict = {i: x for i, x in enumerate(my_dict.items())}
df = pd.DataFrame.from_dict(prepared_dict, orient='index', columns=['business_id', 'business_code'])

Note: I also answered in kind on this similar question.

Share:
51,980
anonuser0428
Author by

anonuser0428

Updated on February 17, 2022

Comments

  • anonuser0428
    anonuser0428 over 2 years

    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'