開始使用免費開始

將臨檢時長轉換為數值

在交通攔查的資料集中,stop_duration 欄位表示員警大約留置駕駛的時間。不過,這些時長是以字串儲存,例如 '0-15 Min'。要怎麼讓這些資料更容易分析呢?

在這個練習中,你會把臨檢時長轉換為整數。由於沒有精確時長,你需要用合理的數值來估計:

  • '0-15 Min' 轉換為 8
  • '16-30 Min' 轉換為 23
  • '30+ Min' 轉換為 45

本練習屬於課程

使用 pandas 分析警方執法活動

檢視課程

練習說明

  • 列印 stop_duration 欄位中的唯一值。(已為你完成。)
  • 建立名為 mapping 的字典,將 stop_duration 的字串對應到指定的整數。
  • 使用 mappingstop_duration 的字串轉換為整數,並將結果儲存到新欄位 stop_minutes
  • 列印 stop_minutes 欄位中的唯一值,以確認時長已正確轉換為整數。

動手互動練習

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

# Print the unique values in 'stop_duration'
print(ri.stop_duration.unique())

# Create a dictionary that maps strings to integers
mapping = {____}

# Convert the 'stop_duration' strings to integers using the 'mapping'
ri['stop_minutes'] = ri.stop_duration.____

# Print the unique values in 'stop_minutes'
print(____)
編輯並執行程式碼