开始使用免费开始使用

提取字符串模式

hiking 数据集中的 Length 列是字符串,但其中包含徒步路线的里程数。我们将使用正则表达式提取该里程数,然后在 pandas 中使用 lambda 将提取逻辑应用到 DataFrame。

本练习是课程的一部分

Python 中的机器学习预处理

查看课程

练习说明

  • length 参数的文本中使用合适的模式搜索整数和小数。
  • 提取匹配的模式并将其转换为浮点数。
  • 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())
编辑并运行代码