1

I have the following working Python polars code. I am learning Rust and am interested in converting Python to Rust.

df = df.with_columns(pl.concat([pl.col(base).slice(0, period).rolling_mean(period), pl.col(base).slice(period,None)]).alias('con'))

How to convert the same in Rust? It might be very trivial, still not sure where I am going wrong.

let rolling_options = RollingOptions {
        window_size : Duration::parse(duration_str.as_str()),
        ..Default::default()
    };
let a = col(base).slice(0,period).rolling_mean(rolling_options);
let b = col(base).slice(period,lit(Null {}));

let temp_df = df.with_column(concat([a, b], UnionArgs::default()));

I keep getting the following error

mismatched types expected enum Expr found enum Result<LazyFrame, PolarsError>

When i checked the data types of a and b, to my surprise they are LazyFrame and not Expr

rolling_mean as per the document returns Expr and so does slice. Not sure what I am missing.

2 Answers 2

4

The result datatype you are getting is an enum meant to represent whether the operation was successful (returns a lazyFrame) or it failed (returns polarserror).

There are a bunch of ways to unwrap (pattern match) an enum, but below are my favorite

foo.unwrap() or foo? if you are using error propagation

This link should cover the different ways to handle errors/results in rust: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html

Sign up to request clarification or add additional context in comments.

1 Comment

Hi Dmitriy_I, Thanks for taking the time to answer the question. I understand the question might have been better, but the answer i was looking for is not the above one. I have got it working after going through the source code of polars. In the above example, i am using concat which takes 2 LazyFrames but i should be using concat_expr instead in case of rust.
1

Working code.

let duration_str = format!("{}{}",usize::try_from(period).unwrap().to_string().as_str(),"i");

let rolling_options = RollingOptions {
    window_size : Duration::parse(duration_str.as_str()),
    min_periods : usize::try_from(period).unwrap(),
    ..Default::default()
};

let lf = df.with_column(concat_expr([col(base).slice(0,period).rolling_mean(rolling_options), 
    col(base).slice(period,lit(Null {}))], false)?.alias("con"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.