You can also use df.into_struct
. Please note that this feature is flagged under dtype-struct
flag
polars = { version = "0.38.1", features = ["dtype-struct"] }
Here how the Rust code looks like:
use polars::prelude::*;
#[derive(Debug)]
pub struct Person {
id: u32,
name: String,
age: u32,
}
fn main() {
let df = df!(
"id" => &[1u32,2,3],
"name" => &["John", "Jane", "Bobby"],
"age" => &[32u32, 28, 45]
)
.unwrap();
let foo: Vec<Person> = df
.into_struct("StructChunked")
.iter()
.map(|row| Person {
id: row[0].try_extract().unwrap(),
name: row[1].get_str().unwrap().to_string(),
age: row[2].try_extract().unwrap(),
})
.collect();
println!("{:?}", foo);
}
This will produce the following output
[Person { id: 1, name: "John", age: 32 }, Person { id: 2, name: "Jane", age: 28 }, Person { id: 3, name: "Bobby", age: 45 }]
EDIT:
It seems like the above code does not work with the latest version of rust-polars(Could be because of breaking changes). Here is the updated code, that work with the latest version.
use polars::prelude::*;
#[derive(Debug)]
pub struct Person {
id: u32,
name: String,
age: u32,
}
fn main() {
let df = df!(
"id" => &[1u32,2,3],
"name" => &["John", "Jane", "Bobby"],
"age" => &[32u32, 28, 45]
)
.unwrap();
let result: Vec<Person> = df
.into_struct("struct")
.into_series()
.iter()
.map(|row: AnyValue<'_>| {
let row_values: Vec<_> = row._iter_struct_av().collect();
Person {
id: row_values[0].try_extract().unwrap(),
name: row_values[1].get_str().unwrap().to_string(),
age: row_values[2].try_extract().unwrap(),
}
})
.collect();
println!("{:?}", result);
}