【问题标题】:SciKit-Learn Label Encoder resulting in error 'argument must be a string or number'SciKit-Learn 标签编码器导致错误“参数必须是字符串或数字”
【发布时间】:2020-03-11 02:08:33
【问题描述】:

我有点困惑 - 在这里创建一个 ML 模型。

我正处于尝试从“大型”数据框(180 列)中获取分类特征并对其进行一次性处理的步骤,以便找到特征之间的相关性并选择“最佳”特征.

这是我的代码:

# import labelencoder
from sklearn.preprocessing import LabelEncoder

# instantiate labelencoder object
le = LabelEncoder()

# apply le on categorical feature columns
df = df.apply(lambda col: le.fit_transform(col))
df.head(10)

运行时出现以下错误:

TypeError: ('argument must be a string or number', 'occurred at index LockTenor')

所以我前往 LockTenor 字段并查看所有不同的值:

df.LockTenor.unique()

这会导致以下结果:

array([60.0, 45.0, 'z', 90.0, 75.0, 30.0], dtype=object)

在我看来就像所有的字符串和数字。错误是因为它是浮点数而不一定是 INT 引起的吗?

【问题讨论】:

  • 您好。如果将 df.apply(lambda col: le.fit_transform(col)) 更改为 df.apply(lambda col: LabelEncoder().fit_transform(col)) 会发生什么?我想知道您的编码器是否对随后的 fit_transform 调用感到困惑,因为它没有被重新初始化。

标签: python machine-learning scikit-learn feature-selection one-hot-encoding


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    您收到此错误是因为您确实有浮点 字符串的组合。看看这个例子:

    # Preliminaries
    import pandas as pd
    from sklearn.preprocessing import LabelEncoder
    
    # Create DataFrames
    
    # df1 has all floats
    d1 = {'LockTenor':[60.0, 45.0, 15.0, 90.0, 75.0, 30.0]}
    df1 = pd.DataFrame(data=d1)
    print("DataFrame 1")
    print(df1)
    
    # df2 has a string in the mix
    d2 = {'LockTenor':[60.0, 45.0, 'z', 90.0, 75.0, 30.0]}
    df2 = pd.DataFrame(data=d2)
    print("DataFrame 2")
    print(df2)
    
    # Create encoder
    le = LabelEncoder()
    
    # Encode first DataFrame 1 (where all values are floats)
    df1 = df1.apply(lambda col: le.fit_transform(col), axis=0, result_type='expand')
    print("DataFrame 1 encoded")
    print(df1)
    
    # Encode first DataFrame 2 (where there is a combination of floats and strings)
    df2 = df2.apply(lambda col: le.fit_transform(col), axis=0, result_type='expand')
    print("DataFrame 2 encoded")
    print(df2)
    

    如果您运行此代码,您将看到 df1 的编码没有问题,因为它的所有值都是浮点数。但是,您将收到您为df2 报告的错误。

    一个简单的解决方法是将列转换为字符串。您可以在相应的 lambda 函数中执行此操作:

    df2 = df2.apply(lambda col: le.fit_transform(col.astype(str)), axis=0, result_type='expand')
    

    作为附加建议,我建议您查看您的数据,看看它们是否正确。对我来说,在同一列中混合使用浮点数和字符串有点奇怪。

    最后,我想指出sci-kit's LabelEncoder performs a simple encoding of variables,它确实执行one-hot编码。如果你想这样做,我建议你看看OneHotEncoder

    【讨论】:

    • 感谢您的成功! z 是我的 NAN 替代品 :)
    • 有趣的选择。我建议你使用 numpy 的 np.nan 或 pandas 的 pd.NA(从 1.0 开始)。这样,您可以使用更多轻松处理缺失值的函数(例如fillna
    • 您好,我也有类似的问题。如果您有时间,可以在此相关帖子上请求您的帮助吗? stackoverflow.com/questions/71193740/…
    猜你喜欢
    • 2020-09-17
    • 2015-12-14
    • 1970-01-01
    • 2020-02-03
    • 2020-12-01
    • 2023-04-09
    • 2020-05-05
    • 2017-05-06
    • 2019-11-04
    相关资源
    最近更新 更多