2

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
3
  • 2
    pd.DataFrame(data, index=[0]) ? Commented Oct 6, 2020 at 21:51
  • 1
    Are you sure you want AssetType to be Motor and not 'Common Stock'? Commented Oct 6, 2020 at 21:54
  • sorry, typo mistakes. I want the asset type to be common stock Commented Oct 6, 2020 at 21:59

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Hello, thanks for your help. In the dictionary, there have 3 pairs of key and value. If I only want to select 2 pairs of key and value to create a dataframe, may I know what can I do?
Several ways - if your data is small, just create a dataframe, and pass in the list of columns you want to keep to the original, something like subset_cols = [c for c in df.columns if c != "Name"]; df = df[subset_cols]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.