开始使用免费开始使用

对类别变量进行编码

UFO 数据集中有几列在用 scikit-learn 建模前需要先进行编码。您将在这里完成该转换,分别使用二元编码和独热编码两种方法。

本练习是课程的一部分

Python 中的机器学习预处理

查看课程

练习说明

  • 使用 apply() 编写条件 lambda 函数:当取值为 "us" 时返回 1,否则返回 0。
  • 打印 type 列中 .unique() 值的数量。
  • 使用 pd.get_dummies()type 列进行独热编码。
  • 最后使用 pd.concat() 将编码后的 type_set 变量拼接回 ufo 数据集。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Use pandas to encode us values as 1 and others as 0
ufo["country_enc"] = ufo["country"].____

# Print the number of unique type values
print(len(____.unique()))

# Create a one-hot encoded set of the type values
type_set = ____

# Concatenate this set back to the ufo DataFrame
ufo = pd.concat([____, ____], axis=1)
编辑并运行代码