Python 将字典转换为熊猫数据框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42466639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a dictionary to a pandas dataframe
提问by user3302483
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:
我正在尝试将只有 1 条记录的字典转换为 Pandas 数据框。我使用了其他解决方案中的以下代码:
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!
回答by Serenity
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
回答by Imran Ahmad Ghazali
Might be you are using python3. in python3 we have list there
可能是您正在使用 python3。在python3中,我们在那里列出
pd.DataFrame(list(d.items()), columns=['id', 'cost','name'])
回答by bunji
An alternative way to create a dataframe with a single row from a dictionary is by creating an empty dataframe first and then append
ingto it:
使用字典中的单行创建数据框的另一种方法是首先创建一个空的数据框,然后对其进行append
ing:
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.
请注意,此方法比 @Serenity 的解决方案慢得多,因此如果您担心性能,请绝对不要选择此方法。但是有选择总是好的。
回答by DeepSpace
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']}
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
:
请记住,如果列顺序很重要,您仍然需要明确提供columns
给DataFrame
:
df = pd.DataFrame(d, columns=['id', 'cost', 'name'])
print(df)
# id cost name
# 0 CS2_056 2 Tap