【问题标题】:LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'LabelEncoder:TypeError:“float”和“str”实例之间不支持“>”
【发布时间】:2018-03-06 12:18:00
【问题描述】:

即使处理缺失值,我也面临多个变量的此错误。 例如:

le = preprocessing.LabelEncoder()
categorical = list(df.select_dtypes(include=['object']).columns.values)
for cat in categorical:
    print(cat)
    df[cat].fillna('UNK', inplace=True)
    df[cat] = le.fit_transform(df[cat])
#     print(le.classes_)
#     print(le.transform(le.classes_))


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-424a0952f9d0> in <module>()
      4     print(cat)
      5     df[cat].fillna('UNK', inplace=True)
----> 6     df[cat] = le.fit_transform(df[cat].fillna('UNK'))
      7 #     print(le.classes_)
      8 #     print(le.transform(le.classes_))

C:\Users\paula.ceccon.ribeiro\AppData\Local\Continuum\Anaconda3\lib\site-packages\sklearn\preprocessing\label.py in fit_transform(self, y)
    129         y = column_or_1d(y, warn=True)
    130         _check_numpy_unicode_bug(y)
--> 131         self.classes_, y = np.unique(y, return_inverse=True)
    132         return y
    133 

C:\Users\paula.ceccon.ribeiro\AppData\Local\Continuum\Anaconda3\lib\site-packages\numpy\lib\arraysetops.py in unique(ar, return_index, return_inverse, return_counts)
    209 
    210     if optional_indices:
--> 211         perm = ar.argsort(kind='mergesort' if return_index else 'quicksort')
    212         aux = ar[perm]
    213     else:

TypeError: '>' not supported between instances of 'float' and 'str'

检查导致错误结果的变量:

df['CRM do Médico'].isnull().sum()
0

除了 nan 值之外,还有什么可能导致此错误?

【问题讨论】:

    标签: python pandas scikit-learn


    【解决方案1】:

    这是由于系列 df[cat] 包含具有不同数据类型的元素,例如(字符串和/或浮点数)。这可能是由于读取数据的方式造成的,即数字被读取为浮点数,文本被读取为字符串,或者数据类型为浮点数并在 fillna 操作后更改。

    换句话说

    pandas数据类型'Object'表示混合类型而不是str类型

    所以使用以下行:

    df[cat] = le.fit_transform(df[cat].astype(str))
    


    应该有帮助

    【讨论】:

    • 确实如此。你知道为什么吗?我已经使用 dtypes 将它们作为 str 读取。
    • 它很可能与pandas中对象类型的定义有关,对象类型不一定是dtype str。并且 pandas 在插入 NaN 值时强制改变类型
    • 什么是le?哪个包?
    • @hhh,syDysregulation 很可能执行了以下导入。从 sklearn.preprocessing 导入 LabelEncoder 作为 le 。 .fit_transform 是赠品。
    • 您好,我也有类似的问题。如果你有时间,可以请求你帮助这个相关的帖子吗? stackoverflow.com/questions/71193740/…
    【解决方案2】:

    由于字符串数据类型具有可变长度,因此默认存储为对象类型。在处理缺失值后,我也遇到了这个问题。在我的情况下,在标签编码工作之前将所有这些列转换为类型“类别”。

    df[cat]=df[cat].astype('category')
    

    然后检查 df.dtypes 并进行标签编码。

    【讨论】:

      【解决方案3】:

      或者使用强制转换为 str 的统一类型

      unique, counts = numpy.unique(str(a).split(), return_counts=True)
      

      【讨论】:

        猜你喜欢
        • 2017-09-22
        • 1970-01-01
        • 2019-11-12
        • 2018-05-19
        • 1970-01-01
        • 1970-01-01
        • 2019-10-24
        • 2020-01-28
        • 2020-08-12
        相关资源
        最近更新 更多