Skip to content Skip to sidebar Skip to footer

Convert A Dictionary To A Pandas Dataframe

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'}

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())
printdf

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
02.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

Post a Comment for "Convert A Dictionary To A Pandas Dataframe"