如何在 Python 中定义数据框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40393663/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:30:01  来源:igfitidea点击:

How do I define a Dataframe in Python?

pythonpandasdataframe

提问by Chase Kregor

I am doing some work in a jupyter notebook using python and pandas and am getting a weird error message and would really appreciate the help. The error I am receiving is "NameError: name 'DataFrame' is not defined"

我正在使用 python 和 Pandas 在 jupyter 笔记本中做一些工作,并收到一条奇怪的错误消息,非常感谢您的帮助。我收到的错误是“NameError: name 'DataFrame' is not defined”

import pandas as pd 

d = {'name': ['Braund', 'Cummings', 'Heikkinen', 'Allen'],
     'age': [22,38,26,35],
     'fare': [7.25, 71.83, 0 , 8.05], 
     'survived?': [False, True, True, False]}

df = DataFrame(d)

print(df)

回答by mikkokotila

The below code works:

以下代码有效:

import pandas as pd 

d = {'name': ['Braund', 'Cummings', 'Heikkinen', 'Allen'],
     'age': [22,38,26,35],
     'fare': [7.25, 71.83, 0 , 8.05], 
     'survived?': [False, True, True, False]}

df = pd.DataFrame(d)

print(df)

Instead of:

代替:

DataFrame(d)

You have to do:

你必须要做:

pd.DataFrame(d)

Because you've imported pandas as 'pd'.

因为您已将熊猫导入为“pd”。

You can achieve the same end much better by:

您可以通过以下方式更好地达到相同的目的:

df = pd.DataFrame({'name': ['Braund', 'Cummings', 'Heikkinen', 'Allen'],
                   'age': [22,38,26,35],
                   'fare': [7.25, 71.83, 0 , 8.05], 
                   'survived': [False, True, True, False]})

I removed the '?' from the 'survived' feature as it's not a good idea to have special characters in your feature names.

我删除了“?” 来自“幸存”功能,因为在功能名称中包含特殊字符不是一个好主意。

回答by RonaldB

The error is not weird. Adding following statement at the top solves the problem:

错误并不奇怪。在顶部添加以下语句可以解决问题:

from pandas import DataFrame