Search code examples
rustrust-polars

List of structs in (Rust) Polars column


Let's say I have a Polars column of type list[list[str]]:

Foos
---
list[list[str]]

[["a", "b"], ["c", "d"], ["e", "f"]]
[["g", "h"], ["i", "j"], ["k", "l"]]
[["m", "n"], ["o", "p"], ["q", "r"]]
...

and a struct Foo:

struct Foo {
    f1: &str,
    f2: &str,
}

How can I obtain a Series list[Foo]?

Foos
---
list[Foo]

[Foo { f1: "a", f2: "b" }, Foo { f1: "c", f2: "d" }, Foo { f1: "e", f2: "f" }]
[Foo { f1: "g", f2: "h" }, Foo { f1: "i", f2: "j" }, Foo { f1: "k", f2: "l" }]
[Foo { f1: "m", f2: "n" }, Foo { f1: "o", f2: "p" }, Foo { f1: "q", f2: "r" }]

I've tried with:

  • ChunkedArray<ObjectType<T>>
  • StructArray<Struct> with fields defined as:
let fields = vec![
    polars::prelude::ArrowField::new("first_name", polars::prelude::ArrowDataType::Utf8, false),
    polars::prelude::ArrowField::new("last_name", polars::prelude::ArrowDataType::Utf8, false),
];

to no avail. Is this at all possible?


Solution

  • Example for a single row:

    let foo = StructChunked::new("foo", 
        &[
            Series::new("f1", ["a", "c", "e"]),
            Series::new("f2", ["b", "d", "f"]),
        ]).unwrap();
    
    foo
    ---
    list[struct[2]]
    
    [{"a","b"}, {"c","d"}, {"e","f"}]