開始使用免費開始

為資料加上標籤

你有一個 DataFrame df,包含欄位 endword(string)、features(vector)與 outvec(vector)。請選出 endword 等於「him」的列,並新增整數欄位 label,其值為 1。接著,使用 union 操作加入相同數量、endword 不等於 him 的列,且這些新增的列其 label = 0。

提醒你,在 SQL 中「不等於」使用 <>

本練習屬於課程

Python Spark SQL 入門

檢視課程

練習說明

  • 匯入 lit 函式。
  • 選出 endword 為 'him' 的列,並新增整數欄位 label,其值為 1。
  • 選出 endword 不為 'him' 的列,並新增整數欄位 label,其值為 0。
  • 將這兩組資料做 union,負向樣本的筆數需與正向樣本相同。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import the lit function
from pyspark.____ import lit

# Select the rows where endword is 'him' and label 1
df_pos = df.where("____ = 'him'")\
           .withColumn('label', lit(____))

# Select the rows where endword is not 'him' and label 0
df_neg = df.where("endword <> '____'")\
           .withColumn('label', ____(0))

# Union pos and neg in equal number
df_examples = df_pos.____(df_neg.limit(df_pos.count()))
print("Number of examples: ", df_examples.count())
df_examples.where("endword <> 'him'").sample(False, .1, 42).show(5)
編輯並執行程式碼