Search code examples
rustrust-polars

No method lazy() found for enum Result when working with Polars dataframes


I'm learning Rust and decided to play with Polars dataframes and getting some errors that I can't understand. The code is simply meant to create a dataframe and then add a new column as the sum of two existing ones:

fn main() {

    let _df = DataFrame::default();

    let df= df!(
        "a" => &[1, 2, 3, 4],
        "b" => &[2, 3, 4, 5],
    );

    println!("{:#?}", df);
    
    let df = df.lazy()
        .with_column(
            col("a") + col("b"),
            "c"
        )
        .collect()
        .unwrap();
}

It fails at the call to the lazy() method:

error[E0599]: no method named `lazy` found for enum `Result` in the current scope
  --> src/bin/dataframes.rs:16:17
   |
16 |     let df = df.lazy()
   |                 ^^^^ method not found in `Result<DataFrame, PolarsError>`
   |
note: the method `lazy` exists on the type `polars::prelude::DataFrame`
  --> /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/polars-lazy-0.35.4/src/frame/mod.rs:45:5
   |
45 |     fn lazy(self) -> LazyFrame;
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: consider using `Result::expect` to unwrap the `polars::prelude::DataFrame` value, panicking if the value is a `Result::Err`

I see the compiler is giving me some potentially useful suggestions, but I don't understand how or where to use Result::expect to unwrap Dataframe value.

I understand that the idea is that out may be either a DataFrame or an error so do I need to add some match construction here?

EDIT Ok, I figured out what to do here but I'm confused because I haven't seen any of this in the official documentation:

    let df = df.expect("").lazy()
        .with_column(
            (col("a") + col("b")).alias("c")
        )
        .collect()
        .unwrap();

Solution

  • polars lazy documentation

    The official document does say df! macro needs to be unwrapped. Though it doesn't explain why.

    Here's the example code in the documentation:

     let df = df! {
         "column_a" => &[1, 2, 3, 4, 5],
         "column_b" => &["a", "b", "c", "d", "e"]
     }.unwrap();
    

    You should check out the official rust book for more explanation on the Result type.

    But for a brief explanation: The Result<T, E> type is returned when a function or macro like df! could evaluate to an error. The enum Result is used to represent that. The user must handle both possibilities with match or other methods.

    result.expect("error message") and result.unwrap() are used to directly extract the T from Result::Ok(T) and crash the program if the result value is a Result::Err(E). This is done usually for convenience during development, but is not recommended for release.