移除注释行
您的主管希望您对一个新的数据集进行一些复杂的解析。该数据表示 ImageNet 数据集的标注信息,但只聚焦于狗的品种,并在图像中识别它们。在进行任何实际分析之前,您需要先清理多处无效或不正确的数据。文档的通用模式未知,因此您希望先将整行导入到单个列中,便于快速分析。
首先,您需要移除数据集中所有的注释行。
spark 上下文和基础 CSV 文件(annotations.csv.gz)已为您准备好可以使用。col 函数也可用。
本练习是课程的一部分
使用 PySpark 进行数据清洗
练习说明
- 将
annotations.csv.gz文件导入为一个 DataFrame 并统计行数。分隔符指定为 |。 - 查询以 # 开头的行数。
- 再次将该文件导入为新的 DataFrame,但在 options 中指定注释字符,以移除所有注释行。
- 统计新 DataFrame 的行数,并验证差异是否符合预期。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import the file to a DataFrame and perform a row count
annotations_df = spark.read.____('____', sep=____)
full_count = annotations_df.____
# Count the number of rows beginning with '#'
comment_count = annotations_df.____(col('_c0').____('#')).count()
# Import the file to a new DataFrame, without commented rows
no_comments_df = ____.____.____('____', ____=____, comment='____')
# Count the new DataFrame and verify the difference is as expected
no_comments_count = no_comments_df.count()
print("Full count: %d\nComment count: %d\nRemaining count: %d" % (____, ____, ____))