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

请求将Polars合并多列至单列的Python代码转译为Rust

Polars Rust实现多列合并为单列(对应Python示例转译)

以下是对应你提供的Python示例的完整Rust可运行代码,同时解决你提到的LazyFrame执行问题:

use polars::prelude::*;

fn main() -> Result<(), PolarsError> {
    let s1 = Series::new("Fruit", &["Apple", "Apple", "Pear"]);
    let s2 = Series::new("Color", &["Red", "Yellow", "Green"]);

    let df = DataFrame::new(vec![s1, s2])?;
    let df_lazy = df.lazy();

    // 实现Python示例中的两个列合并操作
    let result = df_lazy
        .with_columns([
            // 对应Python的pl.format("{} has {} color", "Fruit", "Color")
            col("Fruit")
                .format("{} has {} color", &[col("Color")])
                .alias("fruit_list"),
            // 对应Python的pl.map(["Fruit", "Color"], lambda s: s[0] + " has " + s[1] + " color")
            arr(&[col("Fruit"), col("Color")])
                .map(|arr| {
                    let fruit = arr.str().unwrap().get(0).unwrap().unwrap();
                    let color = arr.str().unwrap().get(1).unwrap().unwrap();
                    Ok(Some(format!("{} has {} color", fruit, color)))
                })
                .alias("fruit_list2"),
        ])
        // 必须显式执行LazyFrame才能获取结果
        .collect()?;

    println!("{}", result);
    Ok(())
}

关键实现说明

  • 对应pl.format的字符串格式化:
    Rust中直接调用Expr::format方法,传入格式字符串和需要插入的列表达式数组,用法和Python逻辑完全对齐,最后用alias指定新列名。

  • 对应pl.map的多列映射:
    先通过arr把多列打包成数组列,再用map遍历每个数组元素。闭包中需要处理字符串类型转换和空值(示例中用unwrap简化处理,生产环境建议根据实际场景做更严谨的错误捕获),最后拼接成目标字符串。

  • 解决LazyFrame执行问题:
    LazyFrame是延迟计算的,必须调用collect()(全量计算)或fetch(n)(获取前n行预览)才能触发计算得到实际的DataFrame。比如简单的select操作示例:

    let selected_df = df_lazy.select([col("Fruit")]).collect()?;
    println!("{}", selected_df);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:05:22