【问题标题】:LabelEncoder specify classes in DataFrameLabelEncoder 在 DataFrame 中指定类
【发布时间】:2016-12-18 00:23:35
【问题描述】:

我正在将 LabelEncoder 应用于 pandas DataFrame,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

我正在将标签编码器应用于这样的数据帧 -

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

这就是标签的映射方式

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

我猜E 没有给出4 的值,因为它没有出现在除Feat 5 之外的任何其他列中。

我希望 E 被赋予 4 的值 - 但不知道如何在 DataFrame 中执行此操作。

【问题讨论】:

  • 你可以使用df.replace({'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4})?

标签: python pandas machine-learning scikit-learn


【解决方案1】:

您可以fit 标签编码器和稍后transform 标签对其标准化编码如下:

In [4]: from sklearn import preprocessing
   ...: import numpy as np

In [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  Feat5
0      0      0      0      0      4
1      1      1      2      2      4
2      2      3      2      2      4
3      3      0      2      3      4

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

In [9]: labels = ['A', 'B', 'C', 'D', 'E']

In [10]: enc = le.fit(labels)

In [11]: enc.classes_                       # sorts the labels in alphabetical order
Out[11]: 
array(['A', 'B', 'C', 'D', 'E'], 
      dtype='<U1')

In [12]: enc.transform('E')
Out[12]: 4

【讨论】:

  • 感谢您的回答 Nickil,但这已将映射更改为 A = 1、B = 2、C = 3、D = 4、E = 0。我可以指定我想要的值吗?
  • 是的,您可以指定需要编码的标签[见编辑的答案]。但是LabelEncoder在内部对它们进行排序并返回排序后的列表。
  • 有没有办法把它放到管道中?
【解决方案2】:

您可以在单个语句中适应和转换, 请找到编码单列并分配回数据框的代码。

df[columnName] = LabelEncoder().fit_transform(df[columnName])

【讨论】:

    猜你喜欢
    • 2020-08-18
    • 2021-12-29
    • 2021-01-21
    • 2023-02-11
    • 2018-07-05
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    相关资源
    最近更新 更多