Convert a dictionary to a pandas dataframe

63,296

Solution 1

You dict has only one record use list:

import pandas as pd
d =  {'id': 'CS2_056', 'cost': 2, 'name': 'Tap'}
df = pd.DataFrame([d], columns=d.keys())
print df

Output:

   id  cost name
0  CS2_056     2  Tap

Solution 2

An alternative way to create a dataframe with a single row from a dictionary is by creating an empty dataframe first and then appending to it:

import pandas as pd 
d =  {'id': 'CS2_056', 'cost': 2, 'name': 'Tap'}
df = pd.DataFrame().append(d, ignore_index=True)
print(df)

   cost       id name
0   2.0  CS2_056  Tap

Note that this method is significantly slower than @Serenity 's solution so definitely do not choose this method if you are concerned about performance. But having options is always nice.

Solution 3

Might be you are using python3. in python3 we have list there

pd.DataFrame(list(d.items()), columns=['id', 'cost','name'])

Solution 4

Easy command, just make sure you enclose your dictionary in square brackets.

d =  {'id': 'CS2_056', 'cost': 2, 'name': 'Tap'}

df = pd.DataFrame([d])
df

Solution 5

While this question does have a duplicate (Python Dictionary to Pandas Dataframe), I believe there's a simplier answer than those provided there.

Convert the values to lists:

d = {'id': ['CS2_056'], 'cost': [2], 'name': ['Tap']}

then simply:

df = pd.DataFrame(d)
print(df)
#     cost       id name
#  0     2  CS2_056  Tap


Keep in mind that if columns order matter you'd still need to explicitly provide columns to DataFrame:

df = pd.DataFrame(d, columns=['id', 'cost', 'name'])
print(df)
#          id  cost name
#  0  CS2_056     2  Tap
Share:
63,296
user3302483
Author by

user3302483

Updated on March 18, 2021

Comments

  • user3302483
    user3302483 about 3 years

    I'm trying to convert a dictionary that only has 1 record to a pandas dataframe. I've used the following code from other solutions:

    d =  {'id': 'CS2_056', 'cost': 2, 'name': 'Tap'}
    
    pd.DataFrame(d.items(), columns=['id', 'cost','name'])
    

    But I get the following error:

    PandasError: DataFrame constructor not properly called!