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

Polars使用str.replace动态模式报错,如何提取URL后缀ID?

解决Polars中str.replace动态模式报错并提取URL后的ID

你遇到的ComputeError: dynamic pattern length in 'str.replace' expressions is not supported yet报错,是因为Polars的str.replace目前不支持将列作为动态模式参数——它要求模式是固定长度的常量字符串,无法处理每行不同的模式值。

针对提取document_url中matching_seed_url之后ID的需求,有两种简洁的解决方案:

方法1:使用str.strip_prefix(推荐)

str.strip_prefix专门用于移除字符串前缀,并且支持列作为前缀参数,完全匹配你的场景:

df = pl.from_repr("""
┌───────────────────────────────┬───────────────────────────┐
│ document_url                  ┆ matching_seed_url         │
│ ---                           ┆ ---                       │
│ str                           ┆ str                       │
╞═══════════════════════════════╪═══════════════════════════╡
│ https://document_url.com/1234 ┆ https://document_url.com/ │
│ https://document_url.com/5678 ┆ https://document_url.com/ │
└───────────────────────────────┴───────────────────────────┘""")

df = df.with_columns(
    pl.when(pl.col("matching_seed_url").is_not_null())
    .then(pl.col("document_url").str.strip_prefix(pl.col("matching_seed_url")))
    .otherwise(pl.lit(""))
    .alias("extracted_id")
)

方法2:使用str.slice + 长度计算

如果需要更灵活的字符串截取逻辑,可以先计算matching_seed_url的长度,再从document_url中截取对应长度之后的部分:

df = df.with_columns(
    pl.when(pl.col("matching_seed_url").is_not_null())
    .then(pl.col("document_url").str.slice(pl.col("matching_seed_url").str.len_bytes()))
    .otherwise(pl.lit(""))
    .alias("extracted_id")
)

两种方法执行后都会得到预期结果:

┌───────────────────────────────┬───────────────────────────┬─────────────┐
│ document_url                  ┆ matching_seed_url         ┆ extracted_id│
│ ---                           ┆ ---                       ┆ ---         │
│ str                           ┆ str                       ┆ str         │
╞═══════════════════════════════╪═══════════════════════════╪═════════════╡
│ https://document_url.com/1234 ┆ https://document_url.com/ ┆ 1234        │
│ https://document_url.com/5678 ┆ https://document_url.com/ ┆ 5678        │
└───────────────────────────────┴───────────────────────────┴─────────────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 20:42:31