使用文字篩選移除紀錄
和客戶多溝通、花時間理解你的變數絕對值得。你發現在不動產產業中,可承擔型貸款並不常見,客戶也建議你把這些案例排除。在這個練習中,我們會使用 isin(),它和 like() 類似,但允許你傳入一個值的清單作為篩選條件,而不是只有單一值。
本練習屬於課程
使用 PySpark 進行特徵工程
練習說明
- 使用
select()和show()檢視欄位'ASSUMABLEMORTGAGE'的不同值,並建立清單yes_values,收集所有包含字串'Yes'的值。 - 使用
~df['ASSUMABLEMORTGAGE']、isin()和.isNull()建立一個 NOT 篩選器,以移除在清單yes_values中對應值的紀錄,並保留空值(null)的紀錄。將此篩選器儲存在變數text_filter中。 - 使用
where()將text_filter套用到df。 - 列印
df中剩餘的筆數。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Inspect unique values in the column 'ASSUMABLEMORTGAGE'
df.____([____]).distinct().____()
# List of possible values containing 'yes'
yes_values = [____, ____]
# Filter the text values out of df but keep null values
text_filter = ~df['ASSUMABLEMORTGAGE'].isin(____) | df['ASSUMABLEMORTGAGE'].isNull()
df = df.____(text_filter)
# Print count of remaining records
print(____.____())