正确的格式与去重用户
看一下 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()