开始使用免费开始使用

为数据打标签

已提供一个名为 df 的 dataframe,包含列 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)
编辑并运行代码