ToDataFrame

Derive Macro ToDataFrame 

Source
#[derive(ToDataFrame)]
{
    // Attributes available to this derive:
    #[df_derive]
}
Expand description

Derive ToDataFrame for structs and tuple structs to generate fast conversions to Polars.

What this macro generates (paths configurable via #[df_derive(...)]):

  • An implementation of ToDataFrame for the annotated type T providing:
    • fn to_dataframe(&self) -> PolarsResult<DataFrame>
    • fn empty_dataframe() -> PolarsResult<DataFrame>
    • fn schema() -> PolarsResult<Vec<(&'static str, DataType)>>
  • An implementation of Columnar for T providing fn columnar_to_dataframe(items: &[Self]) -> PolarsResult<DataFrame>

Supported shapes and types:

  • Named and tuple structs (tuple fields are named field_{index})
  • Nested structs are flattened using dot notation (e.g., outer.inner)
  • Wrappers Option<T> and Vec<T> in any nesting order, with Vec<Struct> producing multiple list columns with a vec_field.subfield prefix
  • Primitive types: String, bool, integer types, f32, f64
  • chrono::DateTime<Utc> (materialized as Datetime(Milliseconds, None))
  • rust_decimal::Decimal (materialized as Decimal(38, 10))

Attributes:

  • Container-level: #[df_derive(trait = "path::ToDataFrame")] to set the ToDataFrame trait path; the Columnar path is inferred by replacing the last path segment with Columnar. Optionally, set both explicitly with #[df_derive(columnar = "path::Columnar")].
  • Field-level: #[df_derive(as_string)] to stringify values (e.g., enums) during conversion, resulting in DataType::String or List<String>.

Notes:

  • Enums and generic structs are not supported for derive.
  • All nested custom structs must also derive ToDataFrame.
  • Empty structs: to_dataframe yields a single-row, zero-column DataFrame; the columnar path yields a zero-column DataFrame with items.len() rows.