简体   繁体   English

将字典转换为熊猫数据框

[英]Convert a dictionary to a pandas dataframe

I'm trying to convert a dictionary that only has 1 record to a pandas dataframe.我正在尝试将只有 1 条记录的字典转换为 Pandas 数据框。 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:您 dict 只有一个记录使用列表:

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

Might be you are using python3.可能是您正在使用 python3。 in python3 we have list there在python3中,我们在那里列出

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

An alternative way to create a dataframe with a single row from a dictionary is by creating an empty dataframe first and then append ing to it:使用字典中的单行创建数据帧的另一种方法是首先创建一个空的数据帧,然后append到它:

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.请注意,此方法比 @Serenity 的解决方案慢得多,因此如果您担心性能,请绝对不要选择此方法。 But having options is always nice.但是有选择总是好的。

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

While this question does have a duplicate ( Python Dictionary to Pandas Dataframe ), I believe there's a simplier answer than those provided there.虽然这个问题确实有重复( Python Dictionary to Pandas Dataframe ),但我相信有一个比那里提供的答案更简单的答案。

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 :请记住,如果列顺序很重要,您仍然需要向DataFrame显式提供columns

df = pd.DataFrame(d, columns=['id', 'cost', 'name'])
print(df)
#          id  cost name
#  0  CS2_056     2  Tap

Passing an index parameter to the DataFrame constructor works in python 3.将索引参数传递给 DataFrame 构造函数适用于 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM