如何从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
相关产品推荐
相关产品推荐

