【问题标题】:TypeError raised while applying 'LabelEncoder's fit_transform' function to columns of object type将“LabelEncoder 的 fit_transform”函数应用于对象类型的列时引发 TypeError
【发布时间】:2020-10-02 12:20:43
【问题描述】:

我正在尝试使用 scikit LabelEncoder 函数将列编码为数字格式。

下面是我的数据框的头部和数据类型。

cc_apps.head()

    0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15
0   b   30.83   0.000   u   g   w   v   1.25    t   t   1   f   g   00202   0   +
1   a   58.67   4.460   u   g   q   h   3.04    t   t   6   f   g   00043   560     +
2   a   24.50   0.500   u   g   q   h   1.50    t   f   0   f   g   00280   824     +
3   b   27.83   1.540   u   g   w   v   3.75    t   t   5   t   g   00100   3   +
4   b   20.17   5.625   u   g   w   v   1.71    t   f   0   f   s   00120   0   +

cc_apps.dtypes
0      object
1      object
2     float64
3      object
4      object
5      object
6      object
7     float64
8      object
9      object
10      int64
11     object
12     object
13     object
14      int64
15     object
dtype: object

以下是我将“对象”类型列转换为数字的操作。

from sklearn.preprocessing import LabelEncoder
le=LabelEncoder()
for col in cc_apps.columns:
    if cc_apps[col].dtype=='object':
        cc_apps[col]=le.fit_transform(cc_apps[col])

TypeError: '<' not supported between instances of 'int' and 'str'
During handling of the above exception, another exception occurred:
TypeError: argument must be a string or number

为什么我会遇到错误?如何克服它?感谢您的投入。

【问题讨论】:

    标签: python-3.x machine-learning scikit-learn data-science


    【解决方案1】:

    satckoverflow本身做了一番研究,发现cc_apps[col]这个对象是混合类型,不同的列有不同的数据类型。因此,le.fit_transform() 要工作,cc_apps[col] 应强制为字符串类型。

    也就是说,代码的编码位如下。这对我有用。

    from sklearn.preprocessing import LabelEncoder
    le=LabelEncoder()
    for col in cc_apps.columns:
        if cc_apps[col].dtype=='object':
            cc_apps[col]=le.fit_transform(cc_apps[col].astype(str))
    

    【讨论】:

      猜你喜欢
      • 2020-08-11
      • 2019-02-25
      • 1970-01-01
      • 2021-09-13
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      相关资源
      最近更新 更多