文字列パターンの抽出
hiking データセットの Length 列は文字列ですが、その中にハイキングの距離(マイル)が含まれています。ここでは正規表現を使ってこの距離を抽出し、pandas のラムダを使って DataFrame 全体に適用していきます。
この演習はコースの一部です
Pythonで学ぶMachine Learningの前処理
演習の手順
length引数の文字列から、数値および小数を探す適切なパターンで検索します。- マッチしたパターンを抽出し、float に変換します。
return_mileage()関数をhiking["Length"]列の各行に適用します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# 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())