在DataFrame中指定LabelEncoder的类别

我正在对一个pandas DataFrame应用LabelEncoder,df

Feat1  Feat2  Feat3  Feat4  Feat5  A      A      A      A      E  B      B      C      C      E  C      D      C      C      E  D      A      C      D      E

我正在对这样的DataFrame应用标签编码器 –

from sklearn import preprocessingle = preprocessing.LabelEncoder()intIndexed = df.apply(le.fit_transform)

标签的映射方式如下

A = 0B = 1C = 2D = 3E = 0

我猜测E没有被赋值为4,因为它只出现在Feat 5列中,而没有出现在其他列中。

我想让E被赋值为4,但我不知道如何在DataFrame中实现这一点。


回答:

您可以先fit标签编码器,然后再transform标签到其标准化编码,如下所示:

In [4]: from sklearn import preprocessing   ...: import numpy as npIn [5]: le = preprocessing.LabelEncoder()In [6]: le.fit(np.unique(df.values))Out[6]: LabelEncoder()In [7]: list(le.classes_)Out[7]: ['A', 'B', 'C', 'D', 'E']In [8]: df.apply(le.transform)Out[8]:    Feat1  Feat2  Feat3  Feat4  Feat50      0      0      0      0      41      1      1      2      2      42      2      3      2      2      43      3      0      2      3      4

默认指定标签的一种方法是:

In [9]: labels = ['A', 'B', 'C', 'D', 'E']In [10]: enc = le.fit(labels)In [11]: enc.classes_                       # 按字母顺序排序标签Out[11]: array(['A', 'B', 'C', 'D', 'E'],       dtype='<U1')In [12]: enc.transform('E')Out[12]: 4

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注