修改 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()