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

Polars中对XML字符串列应用自定义函数创建新列失败的问题求助

Polars中对XML字符串列应用自定义函数创建新列失败的问题求助

看起来你遇到的问题主要是Polars的map_batches和map_elements用法混淆,加上代码里的小拼写错误,还有XML字符串本身的格式问题导致的。我来帮你一步步解决:

先梳理报错的核心原因

  1. map_batches的用法误解:map_batches是接收整个Series作为输入的,但你的func2是为单个XML字符串设计的,所以当它拿到Series的时候就会抛出类型错误,提示需要bytes-like对象而不是Series。
  2. 代码笔误:func2最后返回的是test_list,但你定义的变量是text_list,这也会导致运行错误。
  3. XML格式问题:示例里的XML字符串存在未闭合标签(比如第二个<p>some text<p>),直接用ET.fromstring解析会失败。

修正后的完整代码

import polars as pl
import xml.etree.ElementTree as ET

# 创建示例DataFrame,先修正XML标签的闭合问题
df = pl.DataFrame({
    'A': [1, 2, 3],
    'B': ['<p>some text</p><p>bla</p>', '<p>some text</p><p>foo</p>', '<p>some text</p>']
})

def func(mystring):
    return mystring*2

def func2(xml_string):
    try:
        # 给多根XML节点包裹一层根节点,符合XML单根要求
        root = ET.fromstring(f"<root>{xml_string}</root>")
        text_list = []
        for elem in root.iter():
            text = elem.text.strip() if elem.text else ''
            if text:  # 过滤空文本,避免无效内容
                text_list.append(text)
        return text_list
    except Exception as e:
        print(f"解析XML出错: {e}")
        return []

# 数值列用map_batches没问题,因为func可以处理Series
df = df.with_columns(pl.col("A").map_batches(func).alias('new_col'))
# XML字符串列改用map_elements,逐元素传入单个字符串
df = df.with_columns(pl.col("B").map_elements(func2).alias('new_col2'))

print(df)

关键改动说明

  • 替换map_batches为map_elements:这个方法会逐行把单个字符串传给func2,完美匹配函数的输入预期。
  • 修正笔误:把return test_list改成return text_list。
  • 包裹XML根节点:XML要求有且只有一个根节点,给并列的<p>标签套一层<root>,解决解析报错问题。
  • 添加异常处理:遇到格式错误的XML时,程序不会直接崩溃,而是返回空列表并打印错误信息。
  • 过滤空文本:避免把XML元素里的空字符串也加入结果列表,让输出更干净。

运行结果

shape: (3, 4)
┌─────┬──────────────────────────────────┬─────────┬─────────────────────────┐
│ A   ┆ B                                ┆ new_col ┆ new_col2                │
│ --- ┆ ---                              ┆ ---     ┆ ---                     │
│ i64 ┆ str                              ┆ i64     ┆ list[str]               │
╞═════╪══════════════════════════════════╪═════════╪═════════════════════════╡
│ 1   ┆ <p>some text</p><p>bla</p>       ┆ 2       ┆ ["some text", "bla"]    │
│ 2   ┆ <p>some text</p><p>foo</p>       ┆ 4       ┆ ["some text", "foo"]    │
│ 3   ┆ <p>some text</p>                 ┆ 6       ┆ ["some text"]           │
└─────┴──────────────────────────────────┴─────────┴─────────────────────────┘

备注:内容来源于stack exchange,提问作者JFerro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 11:53:03