You need to enable JavaScript to run this app. R语言如何在data frame中将Years and Month格式时长转总月数并新增Duration列
优惠活动
大模型
产品
解决方案
定价
更多

R语言如何在data frame中将Years and Month格式时长转总月数并新增Duration列

Pandas 时长格式转换实现方案

核心逻辑

针对Years and Month列下形如2Y3M的时长文本,通过正则拆分年、月数值,按「总月数=年数×12 + 月数」计算统一单位的时长结果,将新列插入到目标列相邻位置即可。

分步实现代码

  1. 加载原始数据集
    import pandas as pd
    # 示例数据与你提供的表结构完全匹配
    df = pd.DataFrame({
        "Years and Month": ["2Y3M", "3Y4M"],
        "Percentage Change": ["13%", "23%"]
    })
    
  2. 编写时长转换计算逻辑
    兼容纯年(如4Y)、纯月(如5M)、年+月(如2Y3M)三类常见格式,避免格式不全时报错:
    import re
    def convert_to_month(time_str):
        # 分别匹配Y、M前的数值
        year_match = re.search(r'(\d+)Y', time_str)
        month_match = re.search(r'(\d+)M', time_str)
        years = int(year_match.group(1)) if year_match else 0
        months = int(month_match.group(1)) if month_match else 0
        total_month = years * 12 + months
        # 按示例要求的格式,添加M后缀
        return f"{total_month}M"
    # 生成Duration列的计算结果
    df["Duration"] = df["Years and Month"].apply(convert_to_month)
    
  3. 调整列顺序,将Duration列移到「Years and Month」的相邻位置
    # 获取目标列的位置索引
    target_idx = df.columns.get_loc("Years and Month")
    # 重排列顺序
    col_order = df.columns.tolist()
    col_order.insert(target_idx + 1, col_order.pop(col_order.index("Duration")))
    df = df[col_order]
    

最终输出效果

执行完成后的数据表结构为:

Years and MonthDurationPercentage Change
2Y3M27M13%
3Y4M40M23%

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.07 18:27:02