將臨檢時長轉換為數值
在交通攔查的資料集中,stop_duration 欄位表示員警大約留置駕駛的時間。不過,這些時長是以字串儲存,例如 '0-15 Min'。要怎麼讓這些資料更容易分析呢?
在這個練習中,你會把臨檢時長轉換為整數。由於沒有精確時長,你需要用合理的數值來估計:
- 將
'0-15 Min'轉換為8 - 將
'16-30 Min'轉換為23 - 將
'30+ Min'轉換為45
本練習屬於課程
使用 pandas 分析警方執法活動
練習說明
- 列印
stop_duration欄位中的唯一值。(已為你完成。) - 建立名為
mapping的字典,將stop_duration的字串對應到指定的整數。 - 使用
mapping將stop_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(____)