開始使用免費開始

擷取字串樣式

hiking 資料集裡的 Length 欄位是字串,但其中包含健行路線的里程數。我們要用正規表示式把里程數擷取出來,接著在 pandas 中用 lambda 將這個擷取函式套用到整個 DataFrame。

本練習屬於課程

Python 的 Machine Learning 前處理

檢視課程

練習說明

  • length 參數的文字中,使用合適的樣式搜尋數字與小數。
  • 擷取符合的樣式並將其轉換為 float。
  • hiking["Length"] 欄位的每一列套用 return_mileage() 函式。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Write a pattern to extract numbers and decimals
def return_mileage(length):
    
    # Search the text for matches
    mile = re.____(____, ____)
    
    # If a value is returned, use group(0) to return the found value
    if mile is not None:
        return float(____)
        
# Apply the function to the Length column and take a look at both columns
hiking["Length_num"] = ____.apply(____)
print(hiking[["Length", "Length_num"]].head())
編輯並執行程式碼