將進階轉換套用到 DataFrame
pandas 內建了非常多轉換工具,但有時在轉換時需要更進階的邏輯。apply 函式可讓你把使用者自訂函式套用到 DataFrame 的列或欄,為進階轉換與特徵產生打開大門。
find_street_name() 函式會從 "street_address" 中解析出街道名稱,並從字串中移除門牌號碼。這個函式已載入記憶體,準備好要套用到 raw_testing_scores DataFrame。
本練習屬於課程
使用 Python 的 ETL 與 ELT
練習說明
- 在
transform()函式的定義中,使用find_street_name()函式建立名為"street_name"的新欄位。 - 使用
transform()函式清理raw_testing_scoresDataFrame。 - 列印
cleaned_testing_scoresDataFrame 的前幾列,並觀察新的"street_name"欄位。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def transform(raw_data):
# Use the apply function to extract the street_name from the street_address
raw_data["street_name"] = raw_data.____(
# Pass the correct function to the apply method
____,
axis=1
)
return raw_data
# Transform the raw_testing_scores DataFrame
cleaned_testing_scores = ____(raw_testing_scores)
# Print the head of the cleaned_testing_scores DataFrame
print(cleaned_testing_scores.____())