python - OneHotEncoder categorical_features 已弃用,如何转换特定列
问题描述
我需要将独立字段从字符串转换为算术符号。我正在使用 OneHotEncoder 进行转换。我的数据集有许多独立的列,其中一些是:
Country | Age
--------------------------
Germany | 23
Spain | 25
Germany | 24
Italy | 30
我必须对 Country 列进行编码,例如
0 | 1 | 2 | 3
--------------------------------------
1 | 0 | 0 | 23
0 | 1 | 0 | 25
1 | 0 | 0 | 24
0 | 0 | 1 | 30
我成功通过使用 OneHotEncoder 作为
#Encoding the categorical data
from sklearn.preprocessing import LabelEncoder
labelencoder_X = LabelEncoder()
X[:,0] = labelencoder_X.fit_transform(X[:,0])
#we are dummy encoding as the machine learning algorithms will be
#confused with the values like Spain > Germany > France
from sklearn.preprocessing import OneHotEncoder
onehotencoder = OneHotEncoder(categorical_features=[0])
X = onehotencoder.fit_transform(X).toarray()
现在我收到要使用的折旧消息categories='auto'
。如果我这样做,将对所有独立列(如国家、年龄、工资等)进行转换。
如何仅在数据集第 0 列上实现转换?
解决方案
实际上有2个警告:
FutureWarning:整数数据的处理将在 0.22 版本中发生变化。目前,类别是根据范围 [0, max(values)] 确定的,而将来它们将根据唯一值确定。如果您想要未来的行为并消除此警告,您可以指定“categories='auto'”。如果您在此 OneHotEncoder 之前使用 LabelEncoder 将类别转换为整数,那么您现在可以直接使用 OneHotEncoder。
第二个:
'categorical_features' 关键字在 0.20 版中已弃用,并将在 0.22 版中删除。您可以改用 ColumnTransformer。
“改用 ColumnTransformer。”,弃用警告)
以后不要直接在 OneHotEncoder 中定义列,除非你想使用“categories='auto'”。第一条消息还告诉您直接使用 OneHotEncoder,而不是先使用 LabelEncoder。最后,第二条消息告诉您使用 ColumnTransformer,它类似于用于列转换的管道。
这是您案例的等效代码:
from sklearn.compose import ColumnTransformer
ct = ColumnTransformer([("Name_Of_Your_Step", OneHotEncoder(),[0])], remainder="passthrough")) # The last arg ([0]) is the list of columns you want to transform in this step
ct.fit_transform(X)
另请参阅:ColumnTransformer 文档
对于上面的例子;
编码分类数据(基本上将文本更改为数字数据,即国家名称)
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
#Encode Country Column
labelencoder_X = LabelEncoder()
X[:,0] = labelencoder_X.fit_transform(X[:,0])
ct = ColumnTransformer([("Country", OneHotEncoder(), [0])], remainder = 'passthrough')
X = ct.fit_transform(X)
推荐阅读
- java - 此会话中尚未定义序列“PUBLIC.TEST_ID_SEQ”的当前值;SQL 语句:select currval('test_id_seq')
- laravel - 在同一 /URL 上使用两条路由时 Laravel 'Route Not Defined'
- c# - 无法将文件写入 C# 中的共享文件夹
- django - 如何为两个模型提供外键(以表示活动日志)
- vba - 如何在德国创建 VBA 公式
- hybris - 从云中访问 Spartacus 店面 URL 时在浏览器控制台中出现 CORS 错误
- c# - Razor Collection 绑定故障
- sql - 从表中创建具有嵌套 json 文本的视图 - Postgres
- awk - 用 awk 打印多列,但用分号连接
- sql - 如何将一些记录从一个表复制到另一个