Search code examples
rustrust-polars

How to get a Vec of Structs out of dataframe?


Suppose I've got

use polars::prelude::*;
pub struct Person {
    id: u32,
    name: String,
    age: u32,
}


let df = df!(
    "id" => &[1,2,3],
    "name" => &["John", "Jane", "Bobby"],
    "age" => &[32, 28, 45]
).unwrap();

How can I get a Vec of structs out in place of this fixed definition of rows?

let rows = vec![
    Person { id: 1, name: "John".to_string(), age: 32 },
    Person { id: 2, name: "Jane".to_string(), age: 28 },
    Person { id: 3, name: "Bobby".to_string(), age: 45 },
];

In case anyone's wondering why I ask, I'm trying to use leptos-struct-table with polars built in wasm.


Solution

  • I turned the df into its constituent Series, zipped them together then mapped them into the Person

    let rows:Vec<Person>=
        df.column("id").unwrap().i32().unwrap().into_iter()
        .zip(df.column("name").unwrap().str().unwrap().into_iter())
        .zip(df.column("age").unwrap().i32().unwrap().into_iter())
        .map(|((id, name), age)| {
            Person {
                id:id.unwrap(), 
                name:name.unwrap().to_string(), 
                age:age.unwrap()
            }
        })
        .collect();