开始使用免费开始使用

查看 Schema

正如您在前面章节所学,Spark 对 ALS 的实现要求 movieIduserId 必须是整数类型。为使数据能在 Spark 中正常工作,很多数据集都需要进行相应的预处理。一个常见问题是 Spark 将数字识别成字符串,反之亦然。

在这里,您将使用 .cast() 方法来处理这类问题。我们先查看数据集的 schema,确保其格式正确。

本练习是课程的一部分

使用 PySpark 构建推荐引擎

查看课程

练习说明

  • 使用 .printSchema() 检查评分数据集是否包含 ALS 所需的正确数据类型。userIdmovieId 是否为整数类型?rating 是否为数值格式?
  • 确保 ratings 数据框中的各列数据类型正确。对每一列调用 cast() 方法,将 userIDmovieId 列指定为 "integer" 类型,将 rating 列指定为 "double" 类型。(我们不需要 timestamp 列,可以省略。)
  • 再次对 ratings 调用 .printSchema(),确认数据类型已经正确。

交互式实操练习

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

# Use .printSchema() to see the datatypes of the ratings dataset
ratings.____()

# Tell Spark to convert the columns to the proper data types
ratings = ratings.select(ratings.userId.cast("____"), ratings.movieId.cast("____"), ratings.rating.cast("____"))

# Call .printSchema() again to confirm the columns are now in the correct format
ratings.____()
编辑并运行代码