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

如何在Polars中以整串严格匹配的方式替换字符串值?

如何在Polars中以整串严格匹配的方式替换字符串值?

我来帮你解决这个问题!你遇到的情况是因为str.replace_many()默认是子串匹配——它会把字符串里任何匹配到映射键的片段替换掉,而不是只匹配整个完整字符串。要实现整串严格匹配的替换,有两种简单可行的方法:

方法一:使用replace()方法(推荐)

Polars的列原生方法replace()默认就支持整串完全匹配,刚好契合你的需求。直接用它替代str.replace_many()即可:

import polars as pl

df = pl.DataFrame({
    "Products": ["cell_foo","cell_fooFlex","cell_fooPro"]
})

mapping = { 
    "cell_foo" : "cell", 
    "cell_fooFlex" : "cell", 
    "cell_fooPro": "cell" 
}

# 用replace()实现整串匹配替换
result_df = df.with_columns(
    pl.col("Products").replace(mapping).alias("Replaced")
)

print(result_df)

运行后就能得到你想要的输出:

shape: (3, 2)
┌──────────────┬──────────┐
│ Products     ┆ Replaced │
│ ---          ┆ ---      │
│ str          ┆ str      │
╞══════════════╪══════════╡
│ cell_foo     ┆ cell     │
│ cell_fooFlex ┆ cell     │
│ cell_fooPro  ┆ cell     │
└──────────────┴──────────┘

这个方法的优势在于直观高效,不需要额外处理正则表达式,完全贴合“整串匹配替换”的场景需求。

方法二:给str.replace_many()添加正则锚点(可选)

如果你一定要使用str.replace_many(),可以通过正则表达式的**开头锚点^和结尾锚点$**来强制匹配整个字符串。修改你的映射,给每个键加上锚点即可:

import polars as pl

df = pl.DataFrame({
    "Products": ["cell_foo","cell_fooFlex","cell_fooPro"]
})

# 给每个映射键添加正则锚点,确保整串匹配
regex_mapping = {
    r"^cell_foo$": "cell",
    r"^cell_fooFlex$": "cell",
    r"^cell_fooPro$": "cell"
}

result_df = df.with_columns(
    pl.col("Products").str.replace_many(regex_mapping).alias("Replaced")
)

print(result_df)

这里的^表示字符串的起始位置,$表示结束位置,只有当整个字符串和键完全一致时才会触发替换,最终也能得到预期结果。不过这种方法需要手动处理正则锚点,不如第一种方法简洁。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 11:19:35