開始使用免費開始

從字串擷取數字

UFO 資料集中的 length_of_time 欄位是文字欄位,字串裡包含了以分鐘為單位的數字。這裡你要用正規表示式,從這個文字欄位中擷取出該數字。

本練習屬於課程

Python 的 Machine Learning 前處理

檢視課程

練習說明

  • 使用合適的正規表示式樣式,在 time_string 中搜尋數字。
  • 使用 .apply() 方法,對 length_of_time 欄位的每一列呼叫 return_minutes()
  • 列印 length_of_timeminutes 兩個欄位的 .head(),加以比較。

動手互動練習

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

def return_minutes(time_string):

    # Search for numbers in time_string
    num = re.____(____, ____)
    if num is not None:
        return int(num.group(0))
        
# Apply the extraction to the length_of_time column
ufo["minutes"] = ufo["length_of_time"].____

# Take a look at the head of both of the columns
print(ufo[[____]].head())
編輯並執行程式碼