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

Pandas DataFrame列拆分字符串生成XML标签缺失条目问题咨询

问题排查

你的代码存在3个明确错误:

  • 循环的range参数逻辑错误:你当前遍历的上限是拆分后列表长度的1/2,步长设为2,导致每两对才取一次,漏了最后一对
  • 变量名拼写错误:你定义的列表是xm_list,拼接时错误写成了xml_list,多余的l会触发未定义变量报错
  • 异常捕获逻辑过于宽泛:所有报错都被直接吞掉返回None,你看不到实际的报错信息,增加了排查难度
修正后的代码
def createxm(x):
    try:
        parsedlist = x['strings'].split('|')
        xm_list = []
        # 步长设为2,遍历所有成对的起始索引
        for i in range(0, len(parsedlist), 2):
            # 可选添加:避免列表长度为奇数时索引越界
            if i + 1 >= len(parsedlist):
                break
            xm_list.append('<thekeys db="{}" value="{}"/>'.format(parsedlist[i], parsedlist[i+1]))
        # 所有元素收集完再统一拼接
        xm_string = '\n'.join(xm_list)
        return xm_string
    except Exception as e:
        # 打印报错信息方便排查,不需要可删除
        print(f"处理出错: {e}")
        return None
调用方法
df['new_col'] = df.apply(createxm, axis=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 13:36:06