You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何用正则将DataFrame时分时长字符串转换为总分钟数

解决方案

原有代码问题点

  • 正则逻辑错误:原正则r'[\d+][\d+]'仅能匹配连续2个数字字符,无法适配1位的小时/分钟数值,也不能区分h、m单位对应的数值
  • 取值逻辑未兼容所有场景:当字符串仅包含小时、仅包含分钟、或为empty空值时,re.findall返回的列表长度不足2,直接取下标[0]、[1]会抛出list index out of range错误

调整后实现代码

import re
import pandas as pd

def runtime_to_minutes(string):
    # 预处理字符串,处理空白和empty特殊值
    s = str(string).strip()
    if s == 'empty' or not s:
        # 空值可根据需求改成返回0
        return pd.NA
    # 正则分别捕获小时、分钟数值,两个部分均为可选
    match_res = re.match(r'^(?:(\d+)h)?\s*(?:(\d+)m)?$', s)
    if not match_res:
        return pd.NA
    # 未匹配到的部分默认按0计算
    hours = int(match_res.group(1)) if match_res.group(1) else 0
    minutes = int(match_res.group(2)) if match_res.group(2) else 0
    return hours * 60 + minutes

调用方法

直接对runtime列应用函数即可:

df['minutes'] = df['runtime'].apply(runtime_to_minutes)

适配效果

对应你给出的示例输入,转换结果如下:

runtimeminutes
1h 38m98
20h 4m1204
5h300
45m45
empty

内容的提问来源于stack exchange,提问作者Newbielp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:06:03