添加 ID 字段
处理数据时,您有时只想访问某些字段并执行各种操作。 在本练习中,从 DataFrame 中找出所有"唯一"的投票人姓名,并为其添加唯一的 ID 编号。 请记住,Spark 的 ID 是基于 DataFrame 的"分区"分配的,因此 ID 值可能远大于 DataFrame 实际行数。
由于 Spark 的"惰性"执行,只有在触发 action 时才会真正生成 ID。并且根据数据集大小,ID 看起来可能有些随机。
您的工作区中已提供 spark 会话,以及包含 DallasCouncilVotes.csv.gz 文件的 Spark DataFrame df。并已以别名 F 提供 pyspark.sql.functions 库。
本练习是课程的一部分
使用 PySpark 进行数据清洗
练习说明
- 从
VOTER NAME列选择唯一条目,创建名为voter_df的新 DataFrame。 - 统计
voter_dfDataFrame 的行数。 - 使用合适的 Spark 函数添加一个 ROW_ID 列。
- 展示 ROW_ID 最大的 10 行。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Select all the unique council voters
voter_df = df.____(df["VOTER NAME"]).____()
# Count the rows in voter_df
print("\nThere are %d rows in the voter_df DataFrame.\n" % ____)
# Add a ROW_ID
voter_df = voter_df.____('ROW_ID', F.____())
# Show the rows with 10 highest IDs in the set
voter_df.orderBy(voter_df.____.desc()).show(____)