开始使用免费开始使用

从字符串中提取数字

UFO 数据集中的 length_of_time 字段是文本字段,字符串中包含以分钟为单位的数字。此处,您将使用正则表达式从该文本字段中提取该数字。

本练习是课程的一部分

Python 中的机器学习预处理

查看课程

练习说明

  • 使用合适的正则表达式模式在 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())
编辑并运行代码