janicewww
janicewww

Reputation: 333

Problem of create Pandas Dataframe from dictionary

I have create a Dataframe from a dictionary like this:

import pandas as pd
data = {'Name': 'Ford Motor', 'AssetType': 'Common Stock', 'Exchange': 'NYSE'}

records = []
statement = {}
    
for key, value in data.items():
    statement = {}
    statement[key] = value

    records.append(statement)
df = pd.DataFrame(records)

If I do this way, the output look like this:

    Name        AssetType     Exchange
0   Ford Motor  NaN           NaN
1   NaN         Common Stock  NaN
2   NaN         NaN           NYSE

I want the values on the first row and the result look like this:

    Name    AssetType    Exchange
0   Ford    Common Stock NYSE

Upvotes: 2

Views: 2388

Answers (2)

anon01
anon01

Reputation: 11161

There are a lot of ways you might want to turn data (dict, list, nested list, etc) into a dataframe. Pandas also includes many creation methods, some of which will overlap, making it hard to remember how to create dfs from data. Here are a few ways you could do this for your data:

  • df = pd.DataFrame([data])

  • df = pd.Series(data).to_frame().T

  • pd.DataFrame.from_dict(data, orient="index").T

  • pd.DataFrame.from_records(data, index=[0])

imo, from_dict is the least intuitive (I never get the arguments right on the first try). I find focusing on one construction method to be more memorable than using a different one each time; I use pd.DataFrame(...) and from_records(...) the most.

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195408

Just put data inside a list [] when creating dataframe:

import pandas as pd
data = {'Name': 'Ford Motor', 'AssetType': 'Common Stock', 'Exchange': 'NYSE'}

df = pd.DataFrame([data])
print(df)

Prints:

         Name     AssetType Exchange
0  Ford Motor  Common Stock     NYSE

Upvotes: 2

Related Questions