#![doc(html_root_url = "https://docs.rs/anyvalue-dataframe/0.1.0")]
use std::error::Error;
use polars::prelude::{DataFrame, AnyValue, Schema, Field, DataType};
#[macro_export]
macro_rules! to_any {
($v: expr, DataType::Null) => { AnyValue::Null };
($v: expr, DataType:: $t: ident) => { AnyValue::$t($v) }
}
pub fn row_schema(row: Vec<AnyValue<'_>>) -> polars::frame::row::Row {
polars::frame::row::Row::new(row)
}
pub fn row_fields(desc: Vec<(&str, DataType)>) -> Vec<Field> {
desc.into_iter().map(|(s, t)| Field::new(s, t)).collect()
}
pub fn named_fields(df: &DataFrame, n: Vec<&str>) -> Vec<Field> {
let t = df.dtypes();
row_fields(n.into_iter().enumerate().map(|(i, s)|
(s, t[i].clone())).collect())
}
pub fn named_schema(df: &DataFrame, n: Vec<&str>) -> Schema {
Schema::from_iter(named_fields(&df, n))
}
pub fn df_from_vec(rows: &Vec<polars::frame::row::Row>, n: &Vec<&str>) ->
Result<DataFrame, Box<dyn Error>> {
let schema = Schema::from(&rows[0]);
let mut df = DataFrame::from_rows_iter_and_schema(rows.iter(), &schema)?;
df.set_column_names(&n)?;
Ok(df)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_dataframe() {
let a = to_any!(3, DataType::UInt64);
assert_eq!(a, AnyValue::UInt64(3));
assert_eq!(a.dtype(), DataType::UInt64);
let b = to_any!("A", DataType::Utf8);
assert_eq!(b, AnyValue::Utf8("A"));
assert_eq!(b.dtype(), DataType::Utf8);
let c = to_any!(4, DataType::Int8);
assert_eq!(c, AnyValue::Int8(4));
assert_eq!(c.dtype(), DataType::Int8);
let d = to_any!(1.5, DataType::Float64);
assert_eq!(d, AnyValue::Float64(1.5));
assert_eq!(d.dtype(), DataType::Float64);
let e = to_any!(true, DataType::Boolean);
assert_eq!(e, AnyValue::Boolean(true));
assert_eq!(e.dtype(), DataType::Boolean);
let f = to_any!(&[255, 0], DataType::Binary);
assert_eq!(f, AnyValue::Binary(&[255, 0]));
assert_eq!(f.dtype(), DataType::Binary);
}
}