Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

But I get the following error:

PandasError: DataFrame constructor not properly called!
like image 947
user3302483 Avatar asked Feb 26 '17 09:02

user3302483


2 Answers

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
like image 81
Serenity Avatar answered Sep 22 '22 07:09

Serenity


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.

like image 26
bunji Avatar answered Sep 18 '22 07:09

bunji