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

如何从Pandas列字符串中提取时长并转换为对应天数

实现方案

你之前的写法仅通过非数字字符拆分提取数值,无法关联对应时间单位,改用str.extract捕获数值+单位分组,结合映射规则即可完成转换,完整代码如下:

import pandas as pd

# 时间单位转天数的映射,完全匹配你的预期计算规则:月按30天、年按365天计算
unit_to_days = {
    "week": 7,
    "month": 30,
    "year": 365
}

# 提取数值和时间单位两个分组
df[["time_num", "time_unit"]] = df["column_1"].str.extract(r"(\d+)\s*(week|month|year)", expand=True)
# 转换为天数
df["column_1"] = df["time_num"].astype(int) * df["time_unit"].map(unit_to_days)
# 清理中间辅助列
df.drop(columns=["time_num", "time_unit"], inplace=True)

如果后续需要支持其他时间单位,直接在unit_to_days字典中补充对应天数映射即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:18:03