TypeError: from_dict () got unexpected keyword argument 'columns' in Python

Dung Do Tien Sep 15 2021 159

I have a dictionary object of the view:

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

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

I have tried:

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

But it says it from_dict doesn't take a column argument.

TypeError: from_dict () got unexpected keyword argument 'columns'
Have 2 answer(s) found.
  • J

    Jose Luis Sep 15 2021

    You can loop over the elements:

    pd.DataFrame(list(my_dict.iteritems()),
       columns=['business_id','business_code'])

    #Output

    #       business_id business_code
    0         id2          val2
    1         id3          val3
    2         id1          val1
    
  • N

    Nguyen Quang Thai Sep 15 2021

    To get the same functionality as the documentation and to avoid code workarounds, make sure you are using the most recent version of Pandas. I recently ran into 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 Pandas version and found that I have version 22 running when version 23 is available.

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

    I updated with pip:

    install --upgrade pandas

    I confirmed that my version has been updated to 23 and the same from_dict () code worked without error.

    No code changes are required.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close