Rust Polars 0.37.0中concat_str函数未找到问题求助
Rust Polars 0.37.0 concat_str 找不到的问题解决
问题说明
使用Polars 0.37.0处理CSV文件时,尝试将三个转为String类型的列拼接成新列identifier,Rust代码报[E0425]错误:cannot find function 'concat_str' in this scope,但相同逻辑的Python Polars代码可正常运行。
错误的Rust代码
use polars::prelude::*; use polars_lazy::dsl::functions::*; let df_x = df_a.clone() .lazy() .select([ col("id_turn").cast(DataType::String), col("id_room").cast(DataType::String), col("id_course").cast(DataType::String) ]) .collect()?; let mut df_y = df_x.clone() .lazy() .with_column([ all(), concat_str([col("id_turn"), col("id_room"), col("id_course")],"_",true).alias("identifier") ]) .collect() .unwrap();
正常运行的Python代码
df_x = df_a.with_columns( pl.concat_str( [ pl.col("id_turn"), pl.col("id_room"), pl.col("id_course"), ], separator="_", ).alias("uuid"), )
解决方案
问题根源
- Rust Polars的
concat_str导入路径错误,并非在polars_lazy::dsl::functions下 - Rust与Python的
concat_strAPI参数格式不同,且with_column方法不支持传入数组(需用with_columns) - 代码流程冗余,无需先
collect再重新转为lazy模式
修正后的Rust代码
use polars::prelude::*; let df_y = df_a.clone() .lazy() // 先在lazy pipeline中完成列类型转换 .with_columns([ col("id_turn").cast(DataType::String), col("id_room").cast(DataType::String), col("id_course").cast(DataType::String) ]) // 拼接生成新列 .with_columns([ concat_str([col("id_turn"), col("id_room"), col("id_course")]) .separator("_") .ignore_nulls(true) .alias("identifier") ]) .collect()?;
修正点说明
- 移除错误的
polars_lazy::dsl::functions::*导入,concat_str可从polars::prelude直接获取 - 合并两次lazy操作,避免不必要的
collect和内存拷贝 - 将
with_column改为with_columns(支持多列操作,更符合Polars Rust的API设计) - Rust中
concat_str采用链式调用separator和ignore_nulls方法,与Python的关键字参数逻辑对应 - 去掉冗余的中间变量
df_x和多余的clone,简化代码流程
内容的提问来源于stack exchange,提问作者Jmn
相关产品推荐
相关产品推荐

