访问名为"class"的列时出现SyntaxError.在pandas DataFrame中 [英] SyntaxError when accessing column named "class" in pandas DataFrame

查看:135
本文介绍了访问名为"class"的列时出现SyntaxError.在pandas DataFrame中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为'dataset'的pandas DataFrame,它包含一个名为'class'的列

I have pandas DataFrame named 'dataset' and it contains a column named 'class'

执行以下行时,出现SyntaxError:语法无效

when I execute the following line I get SyntaxError: invalid syntax

print("Unique values in the Class column:", dataset.class.unique())

它适用于其他列名,但不适用于'class'

It works for another column names but not working with 'class'

如何在大熊猫中使用关键字作为列名?

How to use a keyword as column name in pandas ?

推荐答案

class是python中的关键字.经验法则:每当处理不能在python中用作有效变量名的列名时,都必须使用方括号表示法来访问:dataset['class'].unique().

class is a keyword in python. A rule of thumb: whenever you're dealing with column names that cannot be used as valid variable names in python, you must use the bracket notation to access: dataset['class'].unique().

当然,这里有例外,但是它们不利于您的偏爱.例如,min/max是python中的有效变量名(即使它隐藏了内置函数).但是,对于大熊猫,您不能使用属性访问"表示法来引用这样的命名列.文档中已列举了更多此类例外.

There are, of course, exceptions here, but they work against your favour. For example, min/max is a valid variable name in python (even though it shadows builtins). In the case of pandas, however, you cannot refer to such a named column using the Attribute Access notation. There are more such exceptions, they're enumerated in the documentation.

A good place to begin with further reading is the documentation on Attribute Access (specifically, the red Warning box).

这篇关于访问名为"class"的列时出现SyntaxError.在pandas DataFrame中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆