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!
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
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.
Might be you are using python3. in python3 we have list there
pd.DataFrame(list(d.items()), columns=['id', 'cost','name'])