การลบแถวที่ไม่ถูกต้อง
หลังจากลบแถวที่เป็น comment ออกไปแล้ว คุณได้รับข้อมูลเพิ่มเติมเกี่ยวกับรูปแบบทั่วไปของข้อมูล โดย DataFrame ควรมีอย่างน้อย 5 คอลัมน์ที่คั่นด้วย tab เนื่องจาก DataFrame เดิมมีเพียงคอลัมน์เดียว จึงต้องแยกข้อมูลด้วยตัวอักษร tab (\t)
DataFrame annotations_df พร้อมใช้งานแล้ว โดยลบแถว comment ออกไปแล้ว ไลบรารี spark.sql.functions พร้อมใช้งานภายใต้ alias F และจำนวนแถวเริ่มต้นของ DataFrame ถูกเก็บไว้ในตัวแปร initial_count
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การทำความสะอาดข้อมูลด้วย PySpark
คำแนะนำการฝึกหัด
- สร้างตัวแปรใหม่ชื่อ
tmp_fieldsโดยแยกคอลัมน์'_c0'ของ DataFrameannotations_dfด้วยตัวอักษร tab - สร้างคอลัมน์ใหม่ใน
annotations_dfชื่อ'colcount'เพื่อแสดงจำนวนฟิลด์ที่ได้จากขั้นตอนก่อนหน้า - กรองแถวที่มีจำนวนฟิลด์น้อยกว่า 5 ออกจาก
annotations_df - นับจำนวนแถวใน DataFrame และเปรียบเทียบกับ
initial_count
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Split _c0 on the tab character and store the list in a variable
tmp_fields = ____(annotations_df['_c0'], ____)
# Create the colcount column on the DataFrame
annotations_df = annotations_df.____('____', ____(____))
# Remove any rows containing fewer than 5 fields
annotations_df_filtered = annotations_df.____(~ (____))
# Count the number of rows
final_count = ____
print("Initial count: %d\nFinal count: %d" % (initial_count, final_count))