如何在Polars中实现部分匹配时替换整个字符串(含R/Python方案)
R Polars 实现方案
核心需求是只要字符串包含'cats'或'kittens'(忽略大小写),就将整个字符串替换为'CATS',而非仅替换匹配的子串。str$replace_many仅作用于子串替换,不适用此场景,正确做法是结合字符串匹配与条件判断:
- 用
str$contains检测字符串是否匹配正则cats|kittens,开启忽略大小写 - 通过
pl$when()$then()$otherwise()实现整串替换逻辑
完整代码示例
library(polars) # 测试数据 df <- pl$DataFrame( text = c("I love Cats", "Kittens are cute", "Dogs are loyal", "cat and kitten mix") ) # 执行替换 df <- df$with_columns( pl$when(pl$col("text")$str$contains("cats|kittens", ignore_case = TRUE)) $then("CATS") $otherwise(pl$col("text")) $alias("text") ) print(df)
执行结果:
shape: (4, 1) ┌───────────────┐ │ text │ │ --- │ │ str │ ╞═══════════════╡ │ CATS │ │ CATS │ │ Dogs are loyal│ │ CATS │ └───────────────┘
Python Polars 对应方案
逻辑与R Polars完全一致,通过when/then/otherwise配合str.contains实现整串替换:
完整代码示例
import polars as pl # 测试数据 df = pl.DataFrame({ "text": ["I love Cats", "Kittens are cute", "Dogs are loyal", "cat and kitten mix"] }) # 执行替换 df = df.with_columns( pl.when(pl.col("text").str.contains(r"cats|kittens", case=False)) .then("CATS") .otherwise(pl.col("text")) .alias("text") ) print(df)
执行结果:
shape: (4, 1) ┌───────────────┐ │ text │ │ --- │ │ str │ ╞═══════════════╡ │ CATS │ │ CATS │ │ Dogs are loyal│ │ CATS │ └───────────────┘
补充说明
replace_many的设计目标是替换字符串中的匹配子串片段,比如会把"I love Cats"处理成"I love CATS",而非整串替换为"CATS",因此不符合需求。必须通过条件判断直接替换整个单元格的值。
内容的提问来源于stack exchange,提问作者R. Khan
相关产品推荐
相关产品推荐

