修改 DataFrame 列
之前,您已经过滤掉了不大像姓名的行。现在基于您先前的工作,经理要求您创建两个新列——first_name 和 last_name。她希望您把 VOTER_NAME 列按任意空格字符拆分为单词。将最后一个单词当作 last_name,其余所有单词合并为 first_name。在这个练习中,您将使用一些新函数,包括 .split()、.size() 和 .getItem()。其中 .getItem(index) 接受一个整数,用于返回该列中对应序号的项。函数 .split() 和 .size() 位于 pyspark.sql.functions 库中。
请注意,这些操作通常会随具体用例而变化。让数据符合某个约定的格式,往往比格式的细枝末节更重要。数据清洗很少只为某一个人服务——遵循已定义的格式,便于后续共享数据(例如,Paul 不用再操心姓名字段——Mary 已经清理好了数据集)。
上一个练习中过滤后的投票人 DataFrame 以 voter_df 提供。pyspark.sql.functions 库已用别名 F 导入可用。
本练习是课程的一部分
使用 PySpark 进行数据清洗
练习说明
- 新增名为
splits的列,保存可能的姓名列表。 - 使用
getItem()方法创建名为first_name的新列。 - 取出
splits列表的最后一个元素,创建名为last_name的列。 - 删除
splits列,并显示更新后的voter_df。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Add a new column called splits separated on whitespace
voter_df = voter_df.withColumn(____, F.____(voter_df.VOTER_NAME, '\s+'))
# Create a new column called first_name based on the first item in splits
voter_df = voter_df.withColumn(____, voter_df.splits.getItem(____)
# Get the last entry of the splits list and create a column called last_name
voter_df = voter_df.withColumn(____, voter_df.splits.getItem(F.____('splits') - ____))
# Drop the splits column
voter_df = voter_df.____('splits')
# Show the voter_df DataFrame
voter_df.show()