简体   繁体   English

熊猫get_dummies语法错误

[英]pandas get_dummies syntax error

I have a dataset that is 30k in size. 我有一个大小为30k的数据集。 I have a column titled "Native Country" I want to create a new variable for every unique value in that column (the Algorithm I am using can only handle numeric value so I need to convert text to binary form). 我有一个标题为“本国”的列,我想为该列中的每个唯一值创建一个新变量(我使用的算法只能处理数字值,因此我需要将文本转换为二进制形式)。

When I use the following: 当我使用以下命令时:

Native Country = pd.get_dummies(dataset.Native Country , prefix='Native Country' )
Native Country.head()

I get the following error message 我收到以下错误消息

SyntaxError: invalid syntax SyntaxError:语法无效

Any suggestions please. 有任何建议请。

Python identifiers cannot have whitespaces. Python标识符不能有空格。 So you have to use underscore instead of whitespace in variable names. 因此,您必须在变量名中使用下划线而不是空格。 You also have to access column with […] instead of . 您还必须使用[…]而不是访问列. if column name has a whitespace. 如果列名具有空格。

In [1]: import pandas as pd

In [2]: dataset = pd.DataFrame({'Native Country': ['a', 'b', 'a']})

In [6]: native_country = pd.get_dummies(dataset['Native Country'], prefix='Native Country'
   ...: )

In [7]: native_country.head()
Out[7]:
   Native Country_a  Native Country_b
0                 1                 0
1                 0                 1
2                 1                 0

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

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