【问题标题】:Performance wise which is better - Dataframe Map vs Expression in Polars?性能方面哪个更好 - Polars 中的 Dataframe Map 与 Expression?
【发布时间】:2022-09-23 01:44:42
【问题描述】:

我是极地新手。我想基于多列创建一个新列。我可以看到 Expression 很强大,但是对于复杂的逻辑,用casewhen 来解释是相当困难的。

所以我尝试了LazyFrame 中的map,看起来它可以达到目的。但是,我不确定是否会有绩效处罚?或者有没有其他我不知道的更简单的方法。

下面是我的代码Map

    let df = lf
        .map(
            |df: DataFrame| {
                let a = &df[\"a\"];
                let b = &df[\"b\"];
                let r: Series = a
                    .f32()?
                    .into_iter()
                    .zip(b.f32()?.into_iter())
                    .map(|(Some(a), Some(b))| -> i32 {
                        if a * b == 10.0 {
                            10.0
                        } else if a * b == 20.0 {
                            a.cos();
                        } else {
                            b.cos()
                        }
                    })
                    .collect();
                let df_new = DataFrame::new(vec![df[\"c\"], df[r]])?;
                Ok(df_new)
            },
            None,
            None,
        )
        .select(&[
            a.clone().max().alias(\"max\"),
            b.clone().min().alias(\"min\"),
            r.clone().mean().cast(DataType::Float32).alias(\"mean\"),
        ])
        .collect()?;

与下面的表达式相比,

    let r = when((a * b).eq(lit::<f32>(10.0)))
        .then(lit::<f32>(10.0))
        .when((a * b).eq(lit::<f32>(20.0)))
        .then(cos(a))
        .otherwise(cos(b));

    标签: rust rust-polars


    【解决方案1】:

    当您将自定义函数映射到 DataFrame 时,您是在说相信我的优化器,我知道我在做什么。我们无法再进行任何优化。

    除此之外,表达式通常是并行执行的。在您编写的when -&gt; then -&gt; otherwise 表达式中,所有分支都是并行计算的。

    when((a * b).eq(lit::<f32>(10.0)))
            .then(lit::<f32>(10.0))
            .when((a * b).eq(lit::<f32>(20.0)))
            .then(cos(a))
            .otherwise(cos(b));
    

    如果它更快取决于用例。我会说基准。

    但是,您将习惯于在表达式中思考,然后表达式语法变得更加简洁。

    【讨论】:

    • 感谢你的回答。我在您提到的关于使用 chunkedarray 进行三角运算的 GitHub 回复中看到了。我如何在 expr 中使用它?
    • 我认为这更适合另一个 stackoverflow 问题。 ;)
    • 知道了。将创建一个单独的
    猜你喜欢
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 2018-11-05
    相关资源
    最近更新 更多