ihb2032/MoonFrame/frame does not have a README file

    DataFrame

    pub struct DataFrame {
    schema :
    Schema

    columns : Array[
    Series
    ]
    nrows : Int
    name_to_index : Map[String, Int]
    } derive(Eq,
    Debug
    )

    A column-oriented, schema-aware table. DataFrame owns an ordered list of equally-tall Series, a derived Schema, and a private name_to_index cache so column lookup by name is O(1).

    The struct is pub (fields read-only outside the package), so callers always go through the constructors below — those rebuild the cache and the schema in lock-step with the column vector, preserving the invariants:
    • schema.field_names() == columns.map(.name)
    • columns.all(c => c.len() == nrows)
    • name_to_index[name] == i ⇔ columns[i].name == name

    DataFrame::check_invariants

    fn DataFrame::check_invariants(self : DataFrame) -> Result[Unit, String]

    Formal structural specification of DataFrame. check_invariants returns Ok(()) exactly when every invariant the DataFrame docstring promises holds; otherwise it returns Err(msg) naming the first violation it finds.

    This file is the source of truth for what "a well-formed DataFrame" means in MoonFrame v0.1. Constructors and ops are correct iff every output passes check_invariants(). Every *_test.mbt that builds or transforms a frame calls this helper as a final assertion — the closest practical analog to formal verification in MoonBit (real moon prove is overkill for v0.1).

    The invariants checked here, in order:

    INV1 columns.length() == schema.fields().length() INV2 every column has length == nrows INV3 schema.field_names()[i] == columns[i].name() INV4 schema.fields()[i].dtype() == columns[i].dtype() INV5 name_to_index.length() == columns.length() INV6 for every (name, i) in name_to_index: 0 ≤ i < ncols AND columns[i].name() == name INV7 ncols == 0 ⇒ nrows == 0 (a column-less frame is row-less, the 0×0 convention new / empty / from_rows keep)

    Soundness lemma — INV5 ∧ INV6 imply the cache is a bijection onto column indices, hence:
    • column names are unique;
    • every column is reachable by name through the cache. Proof sketch: each cache entry pins a distinct index (two entries with the same i would force their key names equal via INV6 and collapse into one cache slot). With ncols entries each pinning a unique slot in [0, ncols), the relation is a bijection. Consequently we do not separately check "every column has a cache entry" — it's a corollary, and the test budget is better spent on the irredundant checks above.

    DataFrame::column_series

    The columns as Series, in declaration order. A fresh array is returned (the Series themselves are immutable, storage shared), so ops / IO layers can iterate columns directly instead of repeatedly looking each up by name; mutating the returned array can't perturb the frame's invariants.

    DataFrame::columns

    fn DataFrame::columns(self : DataFrame) -> Array[String]

    Column names in declaration order. A fresh array is returned so that mutation by the caller cannot break the schema/columns invariants.

    DataFrame::count

    Non-null cell count of every column as a 1-row Int DataFrame — the row-oriented counterpart of the column-oriented null_count. Total over every dtype (no numeric restriction).

    DataFrame::describe

    Per-column statistical summary, returned as a DataFrame with one row per source column. The result schema is fixed and dtype-pure — every cell has the dtype declared below, regardless of the source frame's shape or column dtypes:

    • column (String): source column name, in declaration order
    • dtype (String): source column dtype rendered via DataType::to_string
    • count (Int): non-null cell count
    • null_count (Int): null cell count
    • n_unique (Int): distinct non-null value count
    • mean (Float, nullable): arithmetic mean for numeric columns; Null for non-numeric or empty / all-null numeric columns
    • min (String, nullable): minimum cell rendered via Scalar::to_string; Null for empty / all-null columns
    • max (String, nullable): maximum cell rendered via Scalar::to_string; Null for empty / all-null columns

    min / max are rendered as String so the summary can carry extrema for every dtype in a single column without forcing a uniform value type. A Float extremum renders via Double::to_string, which drops the decimal point of a whole value (1.0 → "1"), so a Float column's extrema can read like an Int's — the dtype column disambiguates. The per-column reductions (min, max) keep the original dtype if a caller needs it typed.

    This is a deliberately reduced summary: it omits the standard deviation, variance, and quantiles (25% / 50% / 75%) that Polars' describe reports. The per-column kernels expose those directly (Series std / variance / median) for callers who need them.

    Because min / max skip NaN (Polars' regular extrema) while count and n_unique treat NaN as a present value, an all-NaN Float column reports a non-zero count and an n_unique of 1 (every NaN folds into one distinct bucket) but Null min / max — these can legitimately disagree, in addition to the empty / all-null case noted above.

    Raises only because the summary frame is built through the fallible DataFrame::new; the output columns are hardcoded-unique and equal length, so the raise is forwarded, never actually taken. The 0-column case collapses to a 0×8 frame: zero source columns ⇒ zero output rows, but the eight schema columns are still present so downstream code can rely on the result's column layout.

    DataFrame::drop

    Return a copy of self with the columns named by columns removed. Remaining columns keep their relative order — MoonFrame's single drop verb (Polars' df.drop(...)).

    Each entry is an Expr resolved to a column name through the §0 naming rule (Expr::output_name): a bare col("x") names "x", an alias names the alias. The container is Array[Expr] so a future column selector (all / exclude / starts_with) can drop the matched set without a signature change; today only col / aliased keys are meaningful and the expression is never evaluated — only its output name is consulted.

    Duplicate keys are tolerated and act idempotently — dropping [col("a"), col("a")] is the same as dropping [col("a")]. This matches pandas / polars behavior and avoids forcing callers to deduplicate upstream when assembling a drop list from multiple sources.

    Raises:
    • ColumnNotFound(name) — a resolved name does not exist. Reported on the first offending key in columns order.

    Structural invariants on the returned frame follow from DataFrame::new (called with the surviving column subset).

    DataFrame::drop_nulls

    Drop every row in which a gating column has a null cell. The schema (column names, dtypes, order) is preserved verbatim; only the row count shrinks.

    subset selects the gating columns — MoonFrame's single null-dropping verb (Polars' df.drop_nulls(subset)):
    • omitted → every column gates (drop a row null in any column). A 0-column frame is the special case: there are no columns whose validity could fail, so every row passes; with DataFrame::new's convention that a 0-column frame has nrows = 0, the output is structurally identical to the input.
    • Some(keys) → only the columns named by keys gate; a row null in an unlisted column is kept. Each key is an Expr resolved to a column name through the §0 naming rule (Expr::output_name) — a bare col("x") names "x". The Array[Expr] container mirrors drop and leaves room for a future column selector; today only col / aliased keys are meaningful and the expression is never evaluated.
    • Some([]) → no gating columns, so every row passes: a no-op identity, schema preserved.

    Duplicate keys are tolerated and act idempotently; asking the same column to gate twice is the same as asking once.

    Raises:
    • ColumnNotFound(name) — a resolved name does not exist in self. Reported on the first offending key in subset order. (Cannot arise when subset is omitted: the names come straight from the frame.)

    DataFrame::empty

    Build a 0-row DataFrame matching schema. Each column is an empty Series of the field's declared dtype.

    The schema is re-validated through Schema::new (raiseDuplicateColumn(name) on a repeated name): Schema is pub(all), so a caller can build one with duplicate field names by struct literal, bypassing the validating constructor — re-validating here keeps the frame's "no duplicate names" invariant true regardless of how the schema was made.

    raise Unsupported(...) if any field carries DataType::Null — v0.1 has no concrete Null backend (and a CSV-inferred Null column has nothing to materialise into).

    DataFrame::fill_null

    Fill every null cell of the dtype-compatible columns with value, leaving the rest of the frame verbatim — Polars' frame-wide DataFrame.fill_null(value). A column is compatible when its dtype matches value's variant: an Int value fills Int columns, a Float value fills Float columns, and so on. Columns of any other dtype are left untouched (not an error), and so are all columns when value is Scalar::Null — filling nulls with null is a no-op, so it skips everything and returns the frame unchanged.

    Per-column control, cross-dtype fills (an Int value into a Float column, say), or filling with a computed value go through the expression form instead: df.with_columns([col("c").fill_null(lit(value))]).

    Filling rewrites cells in place — each filled column keeps its name and dtype (a compatible fill is dtype-preserving) and every other column is untouched — so names, dtypes, and the row count are unchanged. The returned frame therefore reuses self's schema and O(1) name→index cache verbatim (the same same-schema rebuild head / tail / to_numeric use) rather than re-deriving them through DataFrame::new.

    raise-typed because Series::fill_null is, but the compatibility gate means it is only ever called on a column it cannot fail on (a matching non-null value), so no error is actually produced here.

    DataFrame::filter

    Keep only the rows where predicate evaluates to true — MoonFrame's single row-selection verb. The predicate is an Expr, not a closure: it evaluates vectorized (one column pass, not one call per row), it can be printed, and a lazy Filter node can introspect it for predicate pushdown. A row-wise host predicate is still reachable through the map_many escape hatch — filter(map_many(label~, inputs, f)) reifies the v0.1 closure predicate as a Bool-returning Expr.

    The predicate must evaluate to a Bool column (TypeMismatch otherwise). A row is kept where its cell is true; false and null cells drop the row (the Polars rule — an unknown is not a keep). A length-1 result — a literal, or an aggregation comparison like col("qty").sum().gt(lit_int(0)) — broadcasts over the frame, keeping every row or none.

    The returned frame has the same schema as self (a rejects-everything predicate leaves a 0-row frame with the original schema). A filter that keeps every row returns self unchanged; once any row drops, the surviving cells are re-gathered and each column converges onto the backend its content implies (an all-valid numeric column lands on Numeric) — the engine-wide "backend is a function of content" rule, not a verbatim carry-over. Evaluation errors (unknown columns, dtype mismatches) surface here; building the predicate was total.

    DataFrame::from_rows

    Build a DataFrame from a row-major matrix of Scalars. Each row must have exactly schema.len() cells, and each cell must either match the column's declared dtype or be Scalar::Null.

    Raises:
    • DuplicateColumn(name) — the schema carries a repeated field name. Schema is pub(all), so a caller can construct a duplicate-name schema by struct literal; re-validating through Schema::new here (as empty does) keeps the "no duplicate names" invariant true rather than silently collapsing the name cache.
    • LengthMismatch — a row's width differs from schema.len().
    • TypeMismatch(...) — a non-null cell's dtype doesn't match the schema's dtype for that column.
    • Unsupported(...) — schema declares a Null-dtype column (same reason as empty).
    • NullInNonNullable(name) — a Scalar::Null lands in a column whose field is declared nullable = false.

    DataFrame::get_column

    O(1) lookup of the column named name. raise ColumnNotFound(name) if the column is missing.

    DataFrame::get_column_at

    Column at position i. Out-of-bounds raise IndexOutOfBounds(i).

    DataFrame::group_by

    Partition self into groups by the keys expressions — MoonFrame's single group_by verb (Polars' df.group_by(...)). Rows sharing the same key tuple land in the same group; group order is first appearance (equivalent to Polars' maintain_order=True), so the result is deterministic and snapshot-stable without a sort.

    Each key is an arbitrary expression, evaluated over the whole frame under the rules in expr_eval.mbt, exactly like a sort key: a bare col("region") groups by an existing column, a derived key such as (col("a") + col("b")) groups by the computed value, and a key that reduces to a single cell (a literal, or an aggregation like col("x").sum()) broadcasts over the frame — every row shares it, so it collapses the frame into one group. The materialised key columns head the agg output, each named by its expression's output name (alias, else leftmost column reference, else "literal") and keeping its evaluated dtype.

    Group identity is the composite KeyCell tuple of the row's key cells (see frame/row_key.mbt), hashed on the native cell values, so:
    • a Float NaN collapses into one group — matching Polars, where NaN compares equal for grouping (the same rule join keys on); -0.0 and +0.0 likewise share a group;
    • a null key cell forms its own group rather than being dropped — the Polars default (pandas drops null keys), and the deliberate semantic difference from join, where a null key matches nothing (null != null).

    keys may hold one expression (group_by([col("region")])) or several (group_by([col("region"), col("product")])). An empty keys list places every row in a single group (a grand-total partition); a 0-row frame yields zero groups regardless of keys.

    Raises:
    • ColumnNotFound(name) — a key expression references an absent column. Reported on the first offending key, in keys order.
    • TypeMismatch(...) — a key expression's dtypes don't unify. Reported on the first offending key, in keys order.
    • DuplicateColumn(name) — two keys produce the same output name (which would otherwise have agg emit two identically-named key columns and fail late with a confusing collision). Reported at the second such key, in keys order — mirroring select's per-expression seen-check, and after that key's own evaluation, so an evaluation error there wins over the collision.

    DataFrame::head

    fn DataFrame::head(self : DataFrame, n : Int) -> DataFrame

    First n rows (or all rows if n >= nrows). Negative n clamps to 0. Total — never fails.

    DataFrame::is_empty

    fn DataFrame::is_empty(self : DataFrame) -> Bool

    true when the frame has zero rows. Note that a frame with zero columns and zero rows is also empty (nrows == 0). A 0×N frame (declared schema, no rows yet) is also empty.

    DataFrame::item

    Read the cell at (row, name) as a Scalar, mirroring Polars' DataFrame.item(row, column). Surfaces ColumnNotFound for unknown names and IndexOutOfBounds for row indices outside [0, nrows).

    DataFrame::join

    Equi-join self (the left frame) with other (the right frame) on the key expressions in options.on (or the paired left_on / right_on), producing a new DataFrame.

    Each key is an arbitrary expression, evaluated over the whole frame under the rules in expr_eval.mbt, exactly like a sort / group_by key: options.on is applied to both frames (a bare col("id") joins on an existing column, a derived key such as col("ts") / lit_int(86400) joins on the computed value), while left_on / right_on evaluate position-paired keys on the left and right frame respectively (for differently-named or differently-derived keys). A key that reduces to a single cell (a literal, or an aggregation) broadcasts over the frame.

    Two rows match when every key holds an equal value, using the same composite-KeyCell-tuple encoding group_by uses (see frame/row_key.mbt; the tuple is structurally injective across key columns). The one deliberate difference from group_by: a null key cell matches nothing (null != null, the SQL / Polars default) — such an unmatched row is dropped by Inner and kept (with the other side's columns null) by Left / Right / Outer. A Float NaN key is not null, so — as in group_by, and matching Polars' "NaN compares equal" rule — all NaN keys match each other.

    how selects which unmatched rows survive:
    • Inner — only matched pairs.
    • Left — matched pairs plus every unmatched left row (right columns null).
    • Right — matched pairs plus every unmatched right row (left columns null); the mirror of Left.
    • Outer — matched pairs plus every unmatched row from both sides.
    • Cross — the keyless Cartesian product (see below).

    Output shape:
    • columns = the left columns (original order and names) followed by the right frame's columns (original order). Coalescing applies only to an on join whose every key is a bare col(...) (the only shape where a key names the same column on both sides); left_on / right_on and any derived key never coalesce. Whether an eligible right key column is kept is then governed by options.coalesce (None = auto by how, matching Polars: an inner / left / right join coalesces, an outer join does not). When coalesced, the key appears once at the left key's position, taking each row's value from whichever side is present (the left on Inner / Left, the right on Right, the present side per row on Outer — the two are equal on a matched pair); the right key column is dropped. When not coalesced, the right key column is kept too — it clashes with the left key name, so it gains options.suffix (e.g. id_right) and is null wherever its row had no match. Any other right column whose name occurs in the left frame is likewise suffixed; the left column keeps its name. (A derived key contributes no column of its own — it only decides which rows pair — so the output is just the two frames' columns, the right suffixed on a clash.)
    • rows = left rows in their original order (each with its right matches in ascending right-row order, then — for Left / Outer — unmatched left rows in place with null right columns), followed for Outer by the unmatched right rows in right-row order. A Right join instead emits every right row in right-row order (each with its left matches in ascending left-row order, else the right row alone with null left columns). The order is fully determined by the input order, so results are snapshot-stable.

    how = Cross is the Cartesian product (every left row paired with every right row); it takes no keys, ignores coalesce, and keeps all columns of both frames (suffixing a right column that clashes with a left name). It is the explicit form of what group_by([])'s grand-total group is for aggregation.

    The result routes through DataFrame::new, so it satisfies check_invariants().

    Raises:
    • ColumnNotFound(name) — a key expression references an absent column. Reported on the first offending key, in key order, evaluating the left frame's key before the right's.
    • TypeMismatch(detail) — a key's left and right dtypes differ (so its values could never compare equal), or a derived key's own dtypes don't unify. Reported on the first such key, in key order.
    • InvalidOperation(detail) — no keys for a non-Cross join (use how = Cross for a Cartesian product), any keys on a Cross join (which takes none), both on and left_on / right_on given (they are mutually exclusive), or left_on and right_on of unequal length.
    • DuplicateColumn(name) — either two keys with the same output name (rejected at the repeat during key resolution, like group_by([col("id"), col("id")])), or two output columns still colliding after suffixing (e.g. the left frame already has both value and value_right, and the right contributes a non-key value; surfaced by DataFrame::new).

    DataFrame::max

    Maximum of every column as a 1-row DataFrame. Mirrors min with the order reversed; the NaN-skipping and non-numeric-Null rules are identical.

    DataFrame::mean

    Arithmetic mean of every column as a 1-row DataFrame: numeric columns hold their mean as Float (an empty / all-null numeric column → Null), non-numeric columns a Null cell in their own dtype.

    DataFrame::min

    Minimum of every column as a 1-row DataFrame: numeric columns hold their minimum non-null cell (Float NaN skipped, source dtype preserved), non-numeric columns a Null cell. Note this nulls Bool / String columns rather than ordering them — use Series::min for a typed extremum over any dtype.

    DataFrame::ncols

    fn DataFrame::ncols(self : DataFrame) -> Int

    Number of columns.

    DataFrame::new

    Build a DataFrame from a list of Series. Validates:
    • all columns have the same length (raise LengthMismatch otherwise);
    • no two columns share a name (raise DuplicateColumn(name)).

    Zero columns is valid and produces a 0×0 frame.

    DataFrame::nrows

    fn DataFrame::nrows(self : DataFrame) -> Int

    Number of rows. Equal to every column's len().

    DataFrame::null_count

    Per-column null-count summary, returned as a 1 × ncols DataFrame. Column names match self.columns() verbatim, in the same order, and every output column has dtype Int with a single non-null cell — the null count of the source column.

    The 0-column case collapses to a 0×0 frame: DataFrame::new's "empty column list ⇒ nrows = 0" rule kicks in, and producing a "1×0" frame would otherwise require fabricating a row count without any column to anchor it. Callers that need a guaranteed-nonempty summary should attach a sentinel column before calling.

    Raises only because the summary is built through the fallible DataFrame::new; its failure paths (duplicate-name, length-mismatch) cannot fire here — the names come from self.column_series() (already unique) and every output column has length 1 (or 0 in the 0-column case) — so the raise is forwarded, never actually taken.

    DataFrame::rename

    fn DataFrame::rename(self : DataFrame, mapping : Array[(String, String)]) -> DataFrame raise
    DataError

    Return a copy of self with one or more columns renamed. Renames are applied in input order: each step's new_name becomes visible to subsequent renames, which is what makes the three-step swap [(a, _t), (b, a), (_t, b)] work.

    Raises:
    • ColumnNotFound(old_name) — old_name doesn't exist (or was already renamed away by an earlier step).
    • DuplicateColumn(new_name) — new_name collides with another column that still bears that name at this step.

    An empty mapping is a structural no-op. A (name, name) mapping is a no-op that still validates the source name's existence.

    All structural invariants follow from re-running DataFrame::new at the end, which catches any residual duplicate.

    DataFrame::row

    Row i's cells as a Scalar tuple in column order (a null cell as Scalar::Null), mirroring Polars' DataFrame.row. Row indices outside [0, nrows) raise IndexOutOfBounds(i); for many rows, rows() reads the whole frame in one pass instead.

    DataFrame::rows

    Every row as a Scalar tuple in column order (result[r][c]), the row-major transpose of to_scalar_matrix, mirroring Polars' DataFrame.rows. Total — materialises the frame once.

    DataFrame::schema

    The schema (column names + dtypes + nullability) of this frame.

    DataFrame::select

    Project the frame to exactly the evaluated expressions — MoonFrame's single select verb (Polars' df.select(...)). Each expression is evaluated over the whole frame under the dtype / null / NaN rules in expr_eval.mbt, so a projection can pick an existing column (col("a")), compute a new one (col("a") + col("b")), aggregate (col("a").sum()), or inject a literal. The plain names-only projection of earlier versions is select([col("a"), col("b")]) — or, equivalently, select(cols(["a", "b"])) — and behaves identically: a list of bare col references projects those columns in that order.

    Output height (the Polars select rule). Evaluation yields columns that are frame-tall or length-1 (literals and aggregations):
    • any frame-tall result fixes the height at self.nrows(), and every length-1 result broadcasts up to it — down to zero rows on an empty frame;
    • if every expression reduces to length 1, the output is a single row: df.select([col("a").sum()]) is the one-row summary frame, not nrows copies of it.

    Naming follows with_columns: each column takes its expression's output name (alias, else leftmost column reference, else "literal"), and a name produced twice raises DuplicateColumn at the second expression — errors surface in expression order, before later expressions are evaluated. select([]) collapses to the 0×0 frame.

    Evaluation errors (unknown columns, dtype mismatches, the unrepresentable Null literal) surface here; building the expressions was total.

    DataFrame::shape

    fn DataFrame::shape(self : DataFrame) -> (Int, Int)

    (nrows, ncols).

    DataFrame::slice

    fn DataFrame::slice(self : DataFrame, start : Int, end : Int) -> DataFrame raise
    DataError

    Half-open [start, end) row slice. Bounds checks mirror Series::slice (and BuiltinColumn::slice): out-of-range starts / ends surface as IndexOutOfBounds, start > end as InvalidOperation.

    DataFrame::sort

    Sort self by one or more Expr keys, applied in order — MoonFrame's single sort verb (Polars' df.sort(...)). keys is an array of (key, order, null_order) tuples: a single-key sort passes a one-element array (df.sort([(col("q"), Desc, NullsLast)])), a multi-key sort lists several (df.sort([(col("dept"), Asc, NullsLast), (col("salary"), Desc, NullsLast)])). Earlier keys dominate; later keys only break ties between rows that compare equal under all earlier keys.

    Each key is an arbitrary expression, evaluated over the whole frame under the rules in expr_eval.mbt: a bare col("q") sorts by an existing column, a derived key like col("a") + col("b") sorts by the computed value without materialising it into the output. A key that reduces to a single cell (a literal, or an aggregation such as col("q").sum()) broadcasts over the frame — every row shares it, so it is a stable no-op that leaves earlier keys and the input order untouched.

    The sort is stable (bottom-up merge sort on row indices): two rows that compare equal under every key keep their original relative order. This is what makes [(col("dept"), Asc, _), (col("salary"), Desc, _)] behave the same as "sort by dept, then within each dept sort by salary descending".

    Null and NaN placement is governed by each key's null_order. NaN in a Float key is treated identically to Null for ordering — IEEE 754 makes < / > against NaN return false, so a naive comparator would scatter NaNs unpredictably. (This is the one deliberate departure from Polars, which orders NaN as the largest value and treats only Null as missing.)

    The returned frame routes through DataFrame::take, so the schema (column names, dtypes, order) is preserved verbatim and only the row order changes — the key expressions decide the permutation but never appear in the output. Every output passes check_invariants().

    Evaluation errors surface here (building the keys was total): a key referencing an unknown column raises ColumnNotFound on the first offending key, a dtype clash raises TypeMismatch, and the unrepresentable Null literal raises Unsupported. Every evaluated key is one of Int / Float / Bool / String (there is no Null-dtype backend), so it is always sortable.

    An empty key set is a no-op identity: zero keys ⇒ every comparison returns 0 ⇒ stability preserves the input order.

    DataFrame::storage_kinds

    The storage backend of each column, in declaration order — Numeric for all-valid unboxed numeric columns, Builtin otherwise. Parallel to columns() / the schema's fields.

    DataFrame::sum

    Sum every column as a 1-row DataFrame: numeric columns hold their sum (source dtype preserved), non-numeric columns a Null cell. See the file header for the full semantics. For one column's scalar use df.get_column(name).sum().

    DataFrame::tail

    fn DataFrame::tail(self : DataFrame, n : Int) -> DataFrame

    Last n rows (or all rows if n >= nrows). Negative n clamps to 0. Total — never fails.

    DataFrame::take

    Gather rows by index. Returns a frame whose i-th row is self[indices[i]]. Any out-of-bounds index surfaces as IndexOutOfBounds(idx).

    DataFrame::to_builtin

    fn DataFrame::to_builtin(self : DataFrame) -> DataFrame

    Materialise every column onto the general-purpose Builtin backend (the inverse of to_numeric). Total and lossless — Numeric columns widen with an all-valid bitmap, Builtin columns are unchanged — so names, dtypes, and values are preserved and the schema / lookup cache are reused verbatim.

    DataFrame::to_html

    fn DataFrame::to_html(self : DataFrame) -> String

    Render a DataFrame as an HTML <table>, using the default options (all rows, no class / <caption>, HTML-escaped).

    The output is a <thead> with one <th> per column followed by a <tbody> with one <tr> per record (a <td> per cell, in declaration order); a null cell renders as <td></td>. & / < / > / " / ' are escaped to their HTML entities.

    Empty frames degrade gracefully:
    • 0 columns → returns the empty string (MoonFrame's own choice for a degenerate frame);
    • N columns / 0 rows → header with an empty <tbody>.

    Total — pure string assembly over already-validated frame data.

    DataFrame::to_html_with_options

    fn DataFrame::to_html_with_options(self : DataFrame, options : HtmlOptions) -> String

    Render a DataFrame as an HTML <table> under options — an optional class / <caption>, an optional row cap with a <tfoot> ... (K more rows) banner, and optional escaping. See HtmlOptions.

    Total — options.max_rows is clamped into [0, nrows], so no input can fail.

    DataFrame::to_markdown

    fn DataFrame::to_markdown(self : DataFrame) -> String

    Render a DataFrame as a GitHub-flavored Markdown table.

    The output is three blocks of pipe-bounded rows:
    1. header — column names, one cell per column;
    2. separator — dashes sized to each column;
    3. data — one row per record, in declaration order.

    Column widths are aligned to max(header, every rendered cell), with a 3-character minimum so the dash separator never collapses below the GFM-required floor. Null cells render as the empty string (matching Scalar::to_string), so a null and a genuine empty-string cell render identically — the renderer carries no null marker.

    Empty frames degrade gracefully:
    • 0 columns → returns the empty string;
    • N columns / 0 rows → header + separator with no data rows.

    Total — pure string assembly over already-validated frame data.

    DataFrame::to_markdown_with_limit

    fn DataFrame::to_markdown_with_limit(self : DataFrame, limit : Int) -> String

    Render a DataFrame as a Markdown table, capping the output at the first limit rows. When self has more rows than limit, the truncated count is appended below the table as ... (N more rows). Negative limit is clamped to 0, so a frame that has rows still renders as header + separator + the ... (N more rows) banner; only a genuinely 0-row frame is header + separator alone.

    DataFrame::to_numeric

    fn DataFrame::to_numeric(self : DataFrame) -> DataFrame

    Move every eligible column onto the Numeric fast-path backend, best-effort and total: an all-valid Int / Float column converts; a column carrying nulls, a non-numeric column, or one already Numeric is kept unchanged (via the non-raising try_column_to_numeric, so a column that cannot move never fails the whole frame). Names, dtypes, and values are unchanged — only the backing representation of the converted columns — so the schema and O(1) lookup cache are reused verbatim.

    DataFrame::to_scalar_matrix

    Materialise every column's cells as a column-major matrix of Scalars: result[c][r] is the cell at column c, row r, with Scalar::Null for a null slot (one inner array per column, each nrows long). Equivalent to column_series().map(s => s.to_scalars()), and total — Series::to_scalars is total over every backend.

    This is the one-pass bulk read the row-oriented serialisers (format_csv / the JSON record emitter) share: each materialises the whole frame once, then assembles a record by plain [c][r] indexing rather than a per-cell item, so no row walk pays a repeated bounds-checked lookup. (The table renderers to_html / to_markdown instead scalarise only the visible row window, per column, via table_cell_matrix.)

    DataFrame::unique

    fn DataFrame::unique(self : DataFrame) -> DataFrame

    Drop duplicate rows, keeping the first occurrence of each distinct row — Polars' df.unique(maintain_order=True). Two rows are duplicates when every cell is equal under the same composite KeyCell encoding group_by and join use (see frame/row_key.mbt): a Float NaN equals NaN, -0.0 folds into +0.0, and — like a group_by key — a null cell is an ordinary value, so two rows that are null in the same places (and equal elsewhere) are duplicates. Result rows keep their first-appearance order, so the output is deterministic without a sort. When duplicate rows are dropped, a column that becomes all-valid may converge onto the Numeric fast-path backend — exactly as take / gather do, since the backend is a function of the gathered content, not the source; the schema, values, and frame invariants are unchanged. (An all-distinct frame is returned unchanged, so its backends are untouched.)

    Total: dropping rows from a valid frame can neither change the schema nor fail. A frame whose rows are already all distinct is returned unchanged (the gather would be a no-op), as is a 0-row frame. (Polars' subset / keep parameters — dedup on a column subset, or keep the last / drop all duplicates — are deferred to a later release; this is the all-columns, keep-first form.)

    DataFrame::with_columns

    Evaluate each expression against self and add the results as columns. Derived columns are declared (col("a") + col("b")) rather than pre-materialised (a lit_series(s) carries a ready-made Series). The full construction surface evaluates — arithmetic, comparisons, Kleene logic, not / null probes, aggregations (length-1, broadcast back over the frame), cast, with_alias, when/then/otherwise — under the dtype / null / NaN rules documented in expr_eval.mbt.

    Naming and placement:
    • each result takes its expression's output name — the leftmost column reference, or "literal" for a pure-literal tree (expr_output_name);
    • an output name already present in self replaces that column in place (original position kept);
    • a new output name appends rightmost, in expression order;
    • two expressions producing the same output name raise DuplicateColumn at the second — nothing silently wins.

    Length-1 results (literals) broadcast to nrows — to zero rows on an empty frame. Errors (unknown columns, dtype mismatches, the unrepresentable Null literal) surface here at evaluation time; building the expressions was total. with_columns([]) returns an equal frame.

    GroupedDataFrame

    pub struct GroupedDataFrame {
    source : DataFrame
    key_columns : Array[
    Series
    ]
    groups : Array[Array[Int]]
    } derive(Eq,
    Debug
    )

    A DataFrame partitioned into groups by one or more key expressions, produced by DataFrame::group_by and consumed by agg. Fields are read-only outside the package; the only way to build one is group_by, which guarantees every stored row index is in [0, source.nrows()) and every group is non-empty.

    • source — the frame being grouped (its columns back every aggregation).
    • key_columns — the materialised key columns, one per key expression in the order passed to group_by, each already named by the expression's output name (alias, else leftmost column reference, else "literal") and carrying its evaluated dtype and backend. They head the agg output in this order; agg gathers one representative cell per group from them.
    • groups — one entry per distinct key tuple, in first-appearance order, each holding that group's row indices in ascending row order.

    GroupedDataFrame::agg

    Reduce each group of a grouped frame to one row, evaluating one expression per output column. Each expression is a reduction over its group: col("revenue").sum(), col("revenue").max() -col("revenue").min() (a per-group range), (col("revenue") -col("cost")).sum() (a reduction over a derived column) — the group collapses to a single cell per expression.

    Output shape: the key columns head the frame (in key order, each named by its key expression's output name and keeping its evaluated dtype and backend, one representative row per group), followed by one column per expression (in expression order), named by the expression's output name (alias, else leftmost column reference, else "literal"); one row per group, in the first-appearance group order fixed by group_by. The result routes through DataFrame::new, so name collisions — two expressions sharing an output name, or an expression shadowing a key column — surface as DuplicateColumn, and every output satisfies check_invariants(). agg([]) degenerates to a distinct over the key tuples (zero expressions ⇒ zero aggregated columns).

    Each expression must be reduction-shaped (reduces_per_group): aggregations and literals are per-group scalars, and every combinator — arithmetic / comparison / Kleene operators, not and the null probes, cast, with_alias, when/then/otherwise — preserves scalarness; a bare column reference pins the result to the group height, so it is not a reduction. The check is structural, hence deterministic: agg([col("a")]) raises InvalidOperation even when every group happens to hold a single row, where a dynamic length test would data-dependently pass. (Polars would implicitly collect the group into a list value; MoonFrame has no list dtype, so implicit list-aggregation stays out of scope.)

    Evaluation reuses the expr_eval.mbt engine with scope = each group's row indices, inheriting the documented dtype / null / NaN rules verbatim: sum / mean propagate NaN and reject non-numeric dtypes, min / max skip NaN and are total over every dtype, an all-null group sums to the additive identity and means to a null cell, count counts non-null cells. Dtype errors (ColumnNotFound, TypeMismatch) surface from a probe evaluation under the empty scope before any per-group work; the output dtype is then taken from the reduced cells themselves, since a map(...) closure's result dtype is scope-dependent — the empty-scope probe is only a fallback that types a zero-group or all-null result. Computed columns follow the expression-engine backend convention: an all-valid numeric column converges onto Numeric, anything nullable (or Bool / String) stays Builtin.

    An aggregation directly over a bare column — col(name).<agg>() for any aggregation op, the common case once aliases are peeled — takes a single-pass fast path (bare_col_agg): the shared reduction kernel resolves its reducer and validity mask once and folds each group's row indices straight off the source column, instead of gathering a fresh sub-column per group through the general evaluator. It is purely an optimization — the result is cell-for-cell and backend identical to the general path, with the same dtype / null / NaN rules and the same up-front error surfacing — so an aggregation over a derived operand ((col("a") - col("b")).sum()) transparently falls back to it.

    Raises:
    • InvalidOperation(...) — an expression is not reduction-shaped.
    • ColumnNotFound(name) — an expression references an absent column.
    • TypeMismatch(...) — an expression's dtypes don't unify (e.g. sum over a String column), reported before any group work.
    • DuplicateColumn(name) — two output column names collide.

    HtmlOptions

    pub struct HtmlOptions {
    max_rows : Int?
    table_class : String?
    caption : String?
    escape : Bool
    } derive(Eq,
    Debug
    )

    Options for DataFrame::to_html_with_options. Fields are read-only outside the package — build them through HtmlOptions::default() and chain the with_* setters:

    • max_rows — cap the number of data rows. None (the default) renders every row; Some(n) shows the first n and appends a <tfoot> banner (... (K more rows)) for the remainder. A negative n clamps to 0 (header + banner, no data rows), matching to_markdown_with_limit.
    • table_class — value of the <table class="..."> attribute. None (the default) omits the attribute.
    • caption — text of a leading <caption> element. None (the default) omits it.
    • escape — when true (the default) every emitted string — caption, header names, cell values, and the class attribute — has & / < / > / " / ' rewritten to their HTML entities, so untrusted data can't inject markup. Set false (via with_escape) to pass strings through verbatim for trusted input that intentionally carries HTML.

    HtmlOptions::default

    fn HtmlOptions::default() -> HtmlOptions

    The default options: render all rows, no class, no <caption>, and HTML-escape every emitted string. Chain with_max_rows / with_table_class / with_caption / with_escape to override.

    HtmlOptions::with_caption

    fn HtmlOptions::with_caption(self : HtmlOptions, text : String) -> HtmlOptions

    Return a copy of these options that prepends a <caption> element containing text. Chainable.

    HtmlOptions::with_escape

    fn HtmlOptions::with_escape(self : HtmlOptions, escape : Bool) -> HtmlOptions

    Return a copy of these options with HTML escaping set to escape. Pass false to emit strings verbatim (trusted input that carries intentional markup). Chainable.

    HtmlOptions::with_max_rows

    fn HtmlOptions::with_max_rows(self : HtmlOptions, n : Int) -> HtmlOptions

    Return a copy of these options that caps the rendered table at the first n data rows, appending a <tfoot> ... (K more rows) banner for the remainder. A negative n clamps to 0. Chainable.

    HtmlOptions::with_table_class

    fn HtmlOptions::with_table_class(self : HtmlOptions, cls : String) -> HtmlOptions

    Return a copy of these options whose <table> carries class="<cls>". Chainable.

    JoinOptions

    pub struct JoinOptions {
    on : Array[
    Expr
    ]
    left_on : Array[
    Expr
    ]
    right_on : Array[
    Expr
    ]
    how : JoinType
    suffix : String
    coalesce : Bool?
    } derive(Eq,
    Debug
    )

    The knobs for DataFrame::join: which columns to match on, the join how, the suffix disambiguating a right column whose name collides with a left one, and whether to coalesce the key columns. Fields are read-only outside the package — build options through JoinOptions::on / JoinOptions::left_on / JoinOptions::cross and (optionally) chain with_right_on / with_how / with_suffix / with_coalesce.

    • on — the key expressions, evaluated over both frames (Polars' IntoExpr). A bare col("id") matches on an existing column; a derived key such as col("ts") / lit_int(86400) matches on the computed value. ["region", "product"]-style multi-key joins become [col("region"), col("product")], matched on the tuple. An empty list is a documented cross join (see DataFrame::join).
    • left_on / right_on — paired key expressions evaluated on the left and right frame respectively, for joining on differently-named or differently-derived keys (left_on([col("a")]) against right_on([col("b")])). Mutually exclusive with on, and the two lists must name the same number of keys; key i on the left is matched against key i on the right.
    • how — Inner (the on / left_on default), Left, Right, Outer, or Cross.
    • suffix — appended to a right column whose name also occurs in the left frame (default "_right"); the left column keeps its name.
    • coalesce — whether each key column is merged into a single output column. None (the default) auto-selects by how, matching Polars: an inner / left / right join coalesces (the key appears once), while Outer does not (the right key is kept as <key><suffix>, null wherever its row had no match, so matched and unmatched rows are distinguishable). Some(true) always coalesces; Some(false) never does. Coalescing only applies when keying by on whose every key is a bare col(...) (the precondition for the key to name a single column on both sides); left_on / right_on and any derived key turn it off, keeping both key columns (Polars' "join on a non-column expression turns off coalescing"). When coalesced the single key takes its value from whichever side is present on that row (the two are equal on a matched pair) — the left on Inner / Left, the right on Right, and the present side per row on Outer.

    JoinOptions::cross

    fn JoinOptions::cross() -> JoinOptions

    Start a cross-join specification — the Cartesian product of the two frames, with no key columns (how = Cross, all key lists empty). Keeps the default "_right" collision suffix; coalesce is irrelevant (there are no keys to merge). with_suffix still applies to right columns whose names clash with the left.

    JoinOptions::left_on

    Start a join on differently-named (or differently-derived) keys: the keys are evaluated on the left frame, paired position-by-position with the with_right_on keys evaluated on the right. Defaults match on (inner join, "_right" suffix), except that left_on / right_on keys never coalesce — both key columns are kept (Polars' rule). Chain with_right_on to supply the right-side keys: JoinOptions::left_on([col("a")]).with_right_on([col("b")]).

    JoinOptions::on

    Start a join specification on the keys expressions (applied to both frames), defaulting to an inner join with the "_right" collision suffix and automatic key coalescing (coalesce = None). Chain with_how to switch the join type (Left / Right / Outer), with_suffix to change the suffix, and with_coalesce to force key coalescing on or off: JoinOptions::on([col("id")]).with_how(Left).with_coalesce(true).

    JoinOptions::with_coalesce

    fn JoinOptions::with_coalesce(self : JoinOptions, coalesce : Bool) -> JoinOptions

    Return a copy of these options that forces key coalescing on (coalesce = Some(true), key appears once) or off (coalesce = Some(false), both key columns kept). Overrides the how-derived default. Only effective for an on join whose keys are all bare col(...); left_on / right_on and derived keys never coalesce regardless. Chainable after on / left_on.

    JoinOptions::with_how

    fn JoinOptions::with_how(self : JoinOptions, how : JoinType) -> JoinOptions

    Return a copy of these options with the join how set to how. Chainable after on / left_on.

    JoinOptions::with_right_on

    Return a copy of these options with the right-side keys for a left_on / right_on join set to keys (evaluated on the right frame). Chainable after left_on.

    JoinOptions::with_suffix

    fn JoinOptions::with_suffix(self : JoinOptions, suffix : String) -> JoinOptions

    Return a copy of these options whose right-column collision suffix is suffix instead of the default "_right". Chainable after on / left_on.

    JoinType

    pub(all) enum JoinType {
    Inner
    Left
    Right
    Outer
    Cross
    } derive(Eq,
    Debug
    )

    How an equi-join combines rows that share (or fail to share) a key.

    pub(all) so callers can name the variants directly (e.g. JoinOptions::on(keys).with_how(Left)), matching SortOrder / NullOrder:
    • Inner — keep only rows whose key matches on both sides.
    • Left — keep every left row; where it has no right match, the right-hand columns are filled with nulls.
    • Right — the mirror of Left: keep every right row; where it has no left match, the left-hand columns are filled with nulls. The output still leads with the left columns (only the row set changes to "all right rows").
    • Outer — the full outer join: keep matched pairs plus every unmatched row from both sides (the missing side's columns null). Left rows (matched and unmatched) come first in left order, then the unmatched right rows in right order.
    • Cross — the Cartesian product (every left row paired with every right row); takes no key columns.

    NullOrder

    pub(all) enum NullOrder {
    NullsFirst
    NullsLast
    } derive(Eq,
    Debug
    )

    Where missing cells go relative to non-missing ones. Missing means either a Null slot (validity bit 0) or — for Float columns — NaN. The plan specifies that NaN is treated identically to Null for ordering, so callers don't need a separate knob.

    SortOrder

    pub(all) enum SortOrder {
    Asc
    Desc
    } derive(Eq,
    Debug
    )

    Direction of a sort key. Asc sorts smaller values first, Desc sorts larger values first. The convention applies to every dtype: Int / Float use numeric ordering, Bool uses false < true, String uses lexicographic comparison.