gpt4 book ai didi

python - SciKit-Learn 标签编码器导致错误 'argument must be a string or number'

转载 作者:行者123 更新时间:2023-11-30 08:56:27 25 4
gpt4 key购买 nike

我有点困惑 - 在此处创建 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: ('参数必须是字符串或数字', '发生在索引 LockTenor')

因此,我转到 LockTenor 字段并查看所有不同的值:

df.LockTenor.unique()

这会产生以下结果:

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

对我来说看起来都是字符串和数字。导致错误的原因是它是 float 而不一定是 INT 吗?

最佳答案

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

# 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 的编码没有问题,因为它的所有值都是 float 。但是,您将收到为 df2 报告的错误。

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

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

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

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

关于python - SciKit-Learn 标签编码器导致错误 'argument must be a string or number',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58868256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com