user3302483
user3302483

Reputation: 855

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!

Upvotes: 21

Views: 82297

Answers (6)

DougR
DougR

Reputation: 3479

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

Upvotes: 5

Vishakha Patil
Vishakha Patil

Reputation: 69

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

Upvotes: 0

bunji
bunji

Reputation: 5213

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.

Upvotes: 6

Imran Ahmad Ghazali
Imran Ahmad Ghazali

Reputation: 625

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

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

Upvotes: 8

Serenity
Serenity

Reputation: 36635

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

Upvotes: 55

DeepSpace
DeepSpace

Reputation: 81594

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

Upvotes: 1

Related Questions