对类别变量进行编码
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)