Search code examples
dataframerustrust-polarspolars

Polars Rust equivalent to pl.lit() (repeated value in df)


In python I can construct a dataframe with a repeated value like this:

import polars as pl
df = pl.DataFrame({"foo": [1,2]}).with_columns(bar=pl.lit("baz"))

Can this be done in rust? I'd expect something like:

use polars::prelude::*

let df = df!["foo" => [1,2]].unwrap().with_column(Literal::String("baz"));

but "the trait IntoSeries is not implemented for polars::prelude::LiteralValue". Looking at that trait I can't see any implementers which aren't already collections.

Is the supported way to do this in rust just to construct a vec/series of N repeated values and use that? Or is there some way to have polars handle the repetition itself?


Solution

  • The easiest solution would be to convert your DataFrame into LazyFrame(by calling .lazy() method). Then use the lit function to create a column with literal value.

    use polars::prelude::*;
    
    fn main() {
        let df = df!["foo" => [1,2]]
            .unwrap()
            .lazy()
            .with_column(lit("baz").alias("bar"))
            .collect()
            .unwrap();
        println!("{df}");
    }
    

    If you directly want to operate on DataFrame without converting into Lazyframe, You may need to do some additional work to get that done.

    use polars::prelude::*;
    
    fn main() {
        let mut df = df!["foo" => [1,2]].unwrap();
        df.with_column(Column::new_scalar(
            PlSmallStr::from("bar"),
            Scalar::from(PlSmallStr::from("baz")),
            df.height(),
        ))
        .unwrap();
        println!("{df}")
    }