开始使用免费开始使用

分类变量编码

您的同事已使用 LabelEncoder() 将信用数据集中的列转换为数值。他落下了一列:credit_history,用于记录申请人的信用历史。您希望创建两个版本的数据集。一个使用 LabelEncoder(),另一个使用独热编码,便于对比。特征矩阵已作为 credit 提供。LabelEncoder() 已预加载,且已将 pandas 导入为 pd

本练习是课程的一部分

用 Python 设计机器学习工作流

查看课程

练习说明

  • 使用 LabelEncoder()credit_history 进行编码。
  • 将结果与原始数据框按列连接。
  • 通过将独热编码的虚拟变量与原始数据框按列连接来创建一个新的数据框。
  • 确认独热编码产生的列数多于标签编码。

交互式实操练习

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

# Create numeric encoding for credit_history
credit_history_num = ____.____(
  credit[____])

# Create a new feature matrix including the numeric encoding
X_num = pd.concat([X, pd.Series(____)], ____)

# Create new feature matrix with dummies for credit_history
X_hot = pd.concat(
  [X, ____.____(credit[____])], ____)

# Compare the number of features of the resulting DataFrames
print(X_hot.shape[____] > X_num.shape[____])
编辑并运行代码