I can convert many datatypes into the AnyValue enum in Rust Polars. but how do I convert them back to the original datatypes?
use polars::prelude::*;
fn main() {
let df = df!( "Fruit" => &["Apple", "Apple", "Pear"],
"Boolean" => &[true,false,true],
"Float64" => &[1.1,321.45,101.445])
.unwrap();
// get row 1 of the DataFrame as a vector of AnyValues
let vec_anyvalue = df.get(1).unwrap();
// trying to get the actual values:
// getting the fruit as a String kind of works (get quotation marks too)
let fruit = vec_anyvalue.get(0).unwrap().to_string();
// getting the bool or the float value does not ?!
// ERROR: the trait `From<&AnyValue<'_>>` is not implemented for `bool`
let boolvalue: bool = vec_anyvalue.get(1).unwrap().into();
// ERROR: the trait `From<AnyValue<'_>>` is not implemented for `f64`
let floatvalue: f64 = vec_anyvalue.get(2).unwrap().into();
}
I think you have to write a converter yourself:
fn to_bool<'a>(v: &AnyValue<'a>) -> bool {
if let AnyValue::Boolean(b) = v {
*b
} else {
panic!("not a boolean");
}
}
(or a variation returning Option/Result)