Search code examples
rustrust-polars

How do you create a column of a vector/list type in Polars using Rust


I am trying to create a dataframe in Polars that has a column of fixed size vectors that represent a positions in 2d space. Unfortunately the following does not compile.

let df2 = df!(
    "a" => &[1, 2, 3],
    "b" => &[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]
)?;

I get:

the trait `polars::prelude::NamedFrom<&[[{float}; 2]; 3], _>` is not implemented for `Series`

Can this be done using the Rust API? I could put a column for the x and y coordinates separately, but I actually have multiple columns, some 3D positions, some 4D quaternions. It feels wrong to split them up.


Solution

  • Lists stored in columns use the Series data type and the error you're seeing is that the compiler isn't able to do this conversion for an array of array of floats. You can achieve what you're looking for by converting your nested arrays into series using .iter().collect::<Series>()

    let df = df! {
        "a" => &[1, 2, 3],
        "b" => [[1.0, 2.0].iter().collect::<Series>(), [3.0, 4.0].iter().collect(), [5.0, 6.0].iter().collect()]
    }.unwrap();
    
    
    
    println!("{:?}", df);
    
    shape: (3, 2)
    ┌─────┬────────────┐
    │ a   ┆ b          │
    │ --- ┆ ---        │
    │ i32 ┆ list[f64]  │
    ╞═════╪════════════╡
    │ 1   ┆ [1.0, 2.0] │
    ├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
    │ 2   ┆ [3.0, 4.0] │
    ├╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┤
    │ 3   ┆ [5.0, 6.0] │