pandas get_dummies语法

2024-03-29 04:46:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个30k大小的数据集。我有一个名为“Native Country”的列,我想为该列中的每个唯一值创建一个新变量(我使用的算法只能处理数值,所以我需要将文本转换为二进制形式)。在

当我使用以下选项时:

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

我收到以下错误消息

语法错误:语法无效

有什么建议吗。在


Tags: 数据文本算法getprefix选项二进制country
1条回答
网友
1楼 · 发布于 2024-03-29 04:46:09

Python标识符不能有空格。所以在变量名中必须使用下划线而不是空格。如果列名有空格,则还必须使用[…]而不是{}访问列。在

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

相关问题 更多 >