from sklearn.preprocessing import OneHotEncoder
df.LotFrontage = df.LotFrontage.fillna(value = 0)
categorical_mask = (df.dtypes == "object")
categorical_columns = df.columns[categorical_mask].tolist()
ohe = OneHotEncoder(categories = categorical_mask, sparse = False)
df_encoded = ohe.fit_transform(df)
print(df_encoded[:5, :])
错误:
我可以知道我的代码有什么问题吗?
这是数据片段:
[ 2
无法使用中的categories
参数OneHotEncoder
来选择要编码的功能,因为您需要使用ColumnTransformer
。尝试这个:
df.LotFrontage = df.LotFrontage.fillna(value = 0)
categorical_features = df.select_dtypes("object").columns
column_trans = ColumnTransformer(
[
("onehot_categorical", OneHotEncoder(), categorical_features),
],
remainder="passthrough", # or drop if you don't want the non-categoricals at all...
)
df_encoded = column_trans.fit_transform(df)
请注意,根据docs,Categories参数为
category'auto'或类似数组的列表,默认='auto'
Categories (unique values) per feature: ‘auto’ : Determine categories automatically from the training data. list : categories[i] holds the categories expected in the ith column. The passed categories should not mix strings and numeric
单个功能中的值,如果是数值,则应排序。
因此,它应该包含每个分类功能的每个可能的类别或级别。您可能会使用此方法,因为您知道所有可能的级别,但怀疑您的训练数据可能会省略一些。在您的情况下,我认为您不会;将需要它'auto'
(即默认值)就可以了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句