正確格式與不重複的使用者
查看 R 資料框。你會發現它是傳統的「寬」格式,每一欄代表不同的電影。也請注意,User 和電影名稱並不是整數格式。請依步驟將這份資料正確整理為可用於 ALS 的格式。
本練習屬於課程
使用 PySpark 打造推薦引擎
練習說明
- 從
pyspark.sql.functions匯入monotonically_increasing_id,並使用.show()方法查看R資料框。 - 使用
to_long()函式將R資料框轉換為「長」格式的資料框,並將新資料框命名為ratings。 - 建立名為
users的資料框,內容為資料框中所有.distinct()的使用者,並使用.coalesce(1)將資料重新分割為 1 個分割區。 - 在 users 資料框中,於
withColumn()中使用monotonically_increasing_id()建立一個新欄位,為每位使用者指派唯一的整數。將此欄位命名為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()