开始使用免费开始使用

对分类列进行序数编码

对分类值进行插补相较于数值型要多几个步骤。首先需要把它们转换为数值,因为无法对字符串执行统计运算。

您将使用一家餐厅记录的用户画像数据集,包含顾客偏好与选择。该数据集只有分类特征。在本练习中,您将使用 sklearn 中的 OrdinalEncoder 把分类列 'ambience' 转换为数值。DataFrame 已为您加载为 users。函数 OrdinalEncoder() 也已加载。

users DataFrame 的 head()tail() 已为您打印。

本练习是课程的一部分

在 Python 中处理缺失数据

查看课程

练习说明

  • 创建序数编码器对象,并将其赋给 ambience_ord_enc
  • 选择 users'ambience' 列的非缺失值。
  • ambience_not_null 重塑为形状 (-1, 1)
  • 用编码后的值替换 ambience 的非缺失值。

交互式实操练习

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

# Set col_name to 'ambience'
col_name = 'ambience'
# Create Ordinal encoder
ambience_ord_enc = ___

# Select non-null values of ambience column in users
ambience = users[col_name]
ambience_not_null = ___

# Reshape ambience_not_null to shape (-1, 1)
reshaped_vals = ___

# Select the non-null values for the column col_name in users and store the encoded values
encoded_vals = ambience_ord_enc.fit_transform(reshaped_vals)
users.loc[___, col_name] = np.squeeze(encoded_vals)
编辑并运行代码