【发布时间】:2020-09-28 14:33:43
【问题描述】:
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, :])
错误:
我可以知道我的代码有什么问题吗?
这是数据的sn-p:
[2
【问题讨论】:
-
您能否将
df.head()的结果添加到您的问题中? -
从您的代码看来,
categorical_mask是一个功能名称列表,但文档说 "list : categories[i] 包含第 i 列中预期的类别。" 即它应该是一个列表列表,其中每个内部列表包含每列的实际类别级别(即唯一值)。你得到一个维度不匹配,因为你告诉它每列只有一个唯一值。 -
如果您尝试仅将 OHE 应用于分类列,我建议您改用
ColumnTransformer。看看例子here。然后不要在OHE中指定类别级别,让sklearn推断它们
标签: python pandas scikit-learn one-hot-encoding