我有一个数据集,需要对不同的列执行groupby操作.以下是使用polars版本"0.21.1"的最低工作代码

use polars::prelude::*;
use polars_lazy::prelude::*;
use polars::df;

fn main(){
  let df = df![
    "x1" => ["a", "b", "c", "a"],
    "x2" => ["A", "A", "B", "B"],
    "y" => [1, 2, 3, 4],
    ].unwrap();

  let lf: LazyFrame = df.lazy();

  let out1 = groupby_x1(&lf);
  println!("{:?}", out1.collect());
  let out2 = groupby_x2(&lf);
  println!("{:?}", out2.collect());

}

fn  groupby_x1(lf: &LazyFrame) -> LazyFrame {
  let lf1: LazyFrame = lf.clone().groupby([col("x1")]).agg([
    col("y").sum().alias("y_sum"),
  ]);
  lf1
}

fn  groupby_x2(lf: &LazyFrame) -> LazyFrame {
  let lf1: LazyFrame = lf.clone().groupby([col("x2")]).agg([
    col("y").sum().alias("y_sum"),
  ]);
  lf1
}

但是在代码中,我对整个lazyframe lf进行了深度复制(使用lf.clone().我如何避免呢?如果在函数groupby_x1groupby_x2中用lf替换lf.clone(),我会得到以下错误

error[E0507]: cannot move out of `*lf` which is behind a shared reference
  --> src/main.rs:22:24
   |
22 |   let lf1: LazyFrame = lf.groupby([col("x1")]).agg([
   |                        ^^^^^^^^^^^^^^^^^^^^^^^ move occurs because `*lf` has type `polars_lazy::frame::LazyFrame`, which does not implement the `Copy` trait

error[E0507]: cannot move out of `*lf` which is behind a shared reference
  --> src/main.rs:29:24
   |
29 |   let lf1: LazyFrame = lf.groupby([col("x2")]).agg([
   |                        ^^^^^^^^^^^^^^^^^^^^^^^ move occurs because `*lf` has type `polars_lazy::frame::LazyFrame`, which does not implement the `Copy` trait

For more information about this error, try `rustc --explain E0507`.
error: could not compile `polars_try` due to 2 previous errors

推荐答案

北极星SeriesArc<Vec<ArrowRef>>附近的一种新类型.克隆DataFrame时,仅增加Arc的引用计数.

换句话说,北极星永远不会进行深度克隆.DataFrame的克隆版本非常便宜.

Rust相关问答推荐

如何从使用mockall模拟的方法中返回self?

把Vector3变成Vector4的绝妙方法

使用铁 rust S还原对多个数组执行顺序kronecker积

获取与父字符串相关的&;str的原始片段

我如何使用AWS SDK for Rust获取我承担的角色的凭据?

对于rustc编译的RISC-V32IM二进制文件,llvm objdump没有输出

如何设置activx websocket actorless的消息大小限制?

Rust 中什么时候可以返回函数生成的字符串切片&str?

为什么`tokio::main`可以直接使用而不需要任何导入?

在使用粗粒度锁访问的数据 struct 中使用 RefCell 是否安全?

为什么 Rust 创建的 f32 小于 f32::MIN_POSITIVE?

在 Rust 中查找向量中 dyn struct 的索引

相当于 Rust 中 C++ 的 std::istringstream

无法把握借来的价值不够长寿,请解释

如何在 Rust 中编写涉及异步的重试函数

为什么分配对变量的引用使我无法返回它

Rustfmt 是否有明确类型的选项?

当用作函数参数时,不强制执行与绑定的关联类型

在 Rust 中有条件地导入?

如果返回类型是通用的,我可以返回 &str 输入的一部分吗?