转换分类变量
由于 sklearn 要求模型输入为数值特征,因此需要将分类变量编码为数值变量。最常见的技术是"One-Hot 编码",实现简单,但内存占用较高。为此,您将使用哈希技术,将每个分类列中的类别输入映射为数值。
您的工作环境中已将 pandas 模块导入为 pd,示例 DataFrame 已加载为 df。
本练习是课程的一部分
用 Python 预测 CTR 的机器学习实战
练习说明
- 通过筛选数据类型来选择分类列。
- 对每个分类列应用哈希函数。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Get categorical columns
categorical_cols = df.____(
include = [____]).columns.tolist()
print("Categorical columns: ")
print(categorical_cols)
# Iterate over categorical columns and apply hash function
for col in ____:
df[col] = df[col].____(lambda x: ____(x))
# Print examples of new output
print(df.head(5))