移除稱謂並擷取姓名
在蒐集問卷受訪者的中介資料時,airlines DataFrame 把受訪者的全名存放在 full_name 欄位。不過進一步檢查後,你發現很多名字前面都有稱謂前綴,例如 "Dr."、"Mr."、"Ms." 和 "Miss"。
你的最終目標是建立兩個新欄位 first_name 和 last_name,分別放受訪者的名與姓。在此之前,你需要先移除這些稱謂。
airlines DataFrame 已載入你的環境中,pandas 也已以 pd 載入。
本練習屬於課程
用 Python 進行資料清理
練習說明
- 依序將
full_name中的"Dr."、"Mr."、"Miss"和"Ms."以空字串""取代,來移除它們。 - 使用
.str.contains()執行assert陳述式,測試full_name是否仍包含任何稱謂。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Replace "Dr." with empty string ""
airlines['full_name'] = airlines['full_name'].____.____("____","")
# Replace "Mr." with empty string ""
airlines['full_name'] = ____
# Replace "Miss" with empty string ""
____
# Replace "Ms." with empty string ""
____
# Assert that full_name has no honorifics
assert airlines['full_name'].str.contains('Ms.|Mr.|Miss|Dr.').any() == False