开始使用免费开始使用

正确的格式与去重用户

看一下 R 数据框。它目前是常见的"宽"格式,每一列对应一部不同的电影。还要注意,User 和电影名称都不是整数格式。请按照步骤将这些数据正确准备为可用于 ALS 的格式。

本练习是课程的一部分

使用 PySpark 构建推荐引擎

查看课程

练习说明

  • pyspark.sql.functions 导入 monotonically_increasing_id,并使用 .show() 方法查看 R 数据框。
  • 使用 to_long() 函数把 R 数据框转换为"长"格式的数据框。将新数据框命名为 ratings
  • 创建名为 users 的数据框,其中包含数据框中所有 .distinct() 的用户,并使用 .coalesce(1) 方法将数据框重分区为 1 个分区。
  • withColumn() 中使用 monotonically_increasing_id(),在 users 数据框中创建一个为每位用户分配唯一整数的新列,将该列命名为 userId。请确保对最终的数据框调用 .persist() 方法,以确保新的整数 ID 得以保留。

交互式实操练习

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

# Import monotonically_increasing_id and show R
from pyspark.sql.functions import ____
R.show()

# Use the to_long() function to convert the dataframe to the "long" format.
ratings = to_long(____)
ratings.show()

# Get unique users and repartition to 1 partition
users = ratings.select("____").____().____()

# Create a new column of unique integers called "userId" in the users dataframe.
users = users.withColumn("____", monotonically_increasing_id()).____()
users.show()
编辑并运行代码