20

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!
Serenity
  • 35,289
  • 20
  • 120
  • 115
user3302483
  • 845
  • 4
  • 12
  • 20
  • 2
    Possible duplicate of [Python Dictionary to Pandas Dataframe](http://stackoverflow.com/questions/34589332/python-dictionary-to-pandas-dataframe) – McGrady Feb 26 '17 at 09:08

6 Answers6

55

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
Serenity
  • 35,289
  • 20
  • 120
  • 115
8

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

pd.DataFrame(list(d.items()), columns=['id', 'cost','name'])
Imran Ahmad Ghazali
  • 605
  • 1
  • 10
  • 16
  • I had a dictionary of lists, and I wanted every list to be a cell value under one column, not a series of columns. This gave me an idea how to solve that. – Rafs Aug 21 '23 at 09:36
6

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.

bunji
  • 5,063
  • 1
  • 17
  • 36
5

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
DougR
  • 3,196
  • 1
  • 28
  • 29
1

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
Community
  • 1
  • 1
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
-1

Passing an index parameter to the DataFrame constructor works in python 3.

import pandas as pd

d =  {'id': 'CS2_056', 'cost': 2, 'name': 'Tap'}
df = pd.DataFrame(d, index=[0])
print(df)

# Output:
#           id  cost name
#   0  CS2_056     2  Tap