如何在Rust Polars DataFrame中替换字符串列内容?
Rust Polars:替换DataFrame字符串列内容
解决方案
要替换Text列中所有"foo"为"new foo",可以借助Polars的字符串表达式API,结合with_column实现列更新,核心是str().replace()方法。
完整代码示例
use polars::prelude::*; fn main() -> Result<(), Box<dyn std::error::Error>> { // 构建示例DataFrame let df = df!( "Id" => &[1, 2], "Text" => &["Some foo text", "Other text"] )?; // 替换字符串并覆盖原列 let updated_df = df.with_column( col("Text") .str() .replace(lit("foo"), lit("new foo"), true) // true表示字面量匹配,非正则 .alias("Text") )?; println!("{}", updated_df); Ok(()) }
关键细节解释
col("Text"):定位目标字符串列.str():切换到字符串操作命名空间,启用Polars的字符串处理方法.replace(pattern, replacement, literal):pattern和replacement需用lit()包裹,因为Polars表达式要求用字面量构造器传递常量值literal设为true时按字面文本匹配,设为false则按正则表达式匹配(这里用字面量更贴合需求)
.alias("Text"):指定新列名为原列名,实现覆盖原列的效果with_column:用于添加或替换列,当别名与现有列名一致时,会替换原列
输出结果
运行代码后,得到的DataFrame如下:
shape: (2, 2) ┌─────┬──────────────────┐ │ Id ┆ Text │ │ --- ┆ --- │ │ i32 ┆ str │ ╞═════╪══════════════════╡ │ 1 ┆ Some new foo text│ │ 2 ┆ Other text │ └─────┴──────────────────┘
如果你之前尝试with_column失败,大概率是没有正确使用str()命名空间,或者忘记用lit()包裹字符串常量,Polars的表达式系统对常量传递有严格要求,必须通过lit()来标识。
内容的提问来源于stack exchange,提问作者lucaszane
相关产品推荐
相关产品推荐

