rustrust-polars

Rust Polars upgrade from 46 to 47 diff() function changed and results a runtime error


I am upgrading Polars Rust function from v0.46.0 to v47.1, diff() function broken and the hints Nth(1) not working:

error[E0308]: mismatched types
    --> src/lib.rs:1368:35
     |
1368 |                 col("ticket_price").diff(1,IGNORE).alias("delta"),
     |                              ---- ^ expected `Expr`, found integer
     |                              |
     |                              arguments to this method are incorrect
     |
note: method defined here
    --> /Users/sun/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/polars-plan-0.47.1/src/dsl/mod.rs:1450:12
     |
1450 |     pub fn diff(self, n: Expr, null_behavior: NullBehavior) -> Expr {
     |            ^^^^
help: try wrapping the expression in `polars::prelude::Expr::Nth`
     |
1368 |                 col("ticket_price").diff(polars::prelude::Expr::Nth(1),IGNORE).alias("delta"),
     |                                          +++++++++++++++++++++++++++ +

When I changed to the recommended:

col("ticket_price").diff(polars::prelude::Expr::Nth(1),IGNORE).alias("delta")

I got a runtime error:

called `Result::unwrap()` on an `Err` value: ComputeError(ErrString("'n' must be scalar value\n\nResolved plan until failure:\n\n\t---> FAILED HERE RESOLVING 'sink' <---\nDF [\"name\", \"type\", \"ticket_price\", ...]; PROJECT */5 COLUMNS"))

How do I fix this?


Solution

  • Apparently, you have to wrap the constant in the first argument to diff in lit():

    col("ticket_price").diff(lit(1), IGNORE).alias("delta"),
    

    The suggestion to use Expr::Nth is coming from the rust compiler. It tries to guess the fix based on the types alone, and gets it very wrong in this case.