SciKitLearn标签编码器导致错误“参数必须是字符串或数字”

2024-09-27 00:14:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有点困惑-在这里创建一个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字段,查看所有不同的值:

^{pr2}$

结果如下:array([60.0,45.0,'z',90.0,75.0,30.0],dtype=object)

在我看来,所有的字符串和数字都是这样的……它是不是因为它是一个浮点而不一定是一个整型的错误?在


Tags: 数据模型importledfobject错误分类
1条回答
网友
1楼 · 发布于 2024-09-27 00:14:22

之所以会出现这个错误,是因为您确实有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的编码没有问题,因为它的所有值都是浮点值。不管是谁,您将为df2报告的错误。在

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

^{pr2}$

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

最后,我想指出sci-kit's ^{} performs a simple encoding of variables,它确实执行一个热编码。如果您想这样做,我建议您看看^{}

相关问题 更多 >

    热门问题