Nanuq plans its work with OpenSpec.
The specs in openspec/specs/ describe how Nanuq behaves today: one per capability,
each requirement with a Nim example, its output and the scenarios it must pass. A
change proposes new behavior: a proposal (with its differences from Polars), spec
deltas, sometimes a design, and tasks. Once implemented, it is archived and its deltas
are merged into the specs. The
README explains the
process.
Below, first the changes (open ones first; tick the box to see the archived ones, each
with its proposal, spec deltas and revisions), then every spec in full. Ideas not yet
picked up wait in
BACKLOG.md. The page is
rendered by tools/specview.nim.
Changes
| Change | Stage | Tasks | Specs |
|---|---|---|---|
| add-api-polish | Archived | 11/11 | data-types ~1dataframe-api +3 ~2expressions +1frame-verbs ~1missing-values ~4native-bridge ~1 |
| add-arraymancer-interop | Archived | 3/3 | arraymancer-interop +2 |
| add-arrow-c-data | Archived | 3/3 | arrow-interop +3 |
| add-binary-decimal-bitwise | Archived | 3/3 | binary-decimal +4 |
| add-book-port-needs | Archived | 7/7 | dataframe-api ~1expressions +1frame-verbs +1missing-values +1 |
| add-book-port-needs-0-5 | Archived | 6/6 | expressions +2frame-verbs +2list-functions +1series +3struct-functions +1 |
| add-book-port-needs-0-6 | Archived | 4/4 | column-selectors +1expressions +1frame-verbs +4inspection +1 |
| add-categoricals | Archived | 8/8 | categoricals +3data-types ~2native-bridge ~1 |
| add-cloud-storage | Archived | 4/4 | cloud-storage +3 |
| add-column-access-and-nulls | Archived | 12/12 | dataframe-api ~1missing-values +7native-bridge +1 |
| add-column-selectors | Archived | 10/10 | column-selectors +5native-bridge ~1 |
| add-coverage-easy-wins-0-6 | Archived | 5/5 | csv-io +1excel-io +1expressions +2frame-utilities +5inspection +1parquet-ipc +2series +1strings +1temporal +2 |
| add-csv-options-and-scan | Archived | 9/9 | csv-io +3native-bridge ~1 |
| add-cumulative-and-shift | Archived | 4/4 | cumulative-functions +4expressions +1 |
| add-database-io | Archived | 2/2 | database-io +2 |
| add-datamancer-interop | Archived | 6/6 | datamancer-interop +4 |
| add-datatype-and-cast | Archived | 10/10 | data-types +4native-bridge ~1 |
| add-devlog-index | Archived | 7/7 | ci ~1dev-log +2 |
| add-dynamic-group-by | Archived | 4/4 | temporal-grouping +3 |
| add-excel-io | Archived | 3/3 | excel-io +2 |
| add-explainer-needs-0-5 | Archived | 4/4 | frame-verbs +2missing-values +1 |
| add-explainer-needs-0-6 | Archived | 3/3 | binary-decimal +2csv-io +1data-types +1 |
| add-expr-essentials | Archived | 13/13 | expressions +8native-bridge ~1 |
| add-expr-filter | Archived | 3/3 | column-selectors ~1expressions +1 |
| add-expr-math | Archived | 4/4 | math-functions +5 |
| add-expression-plugins | Archived | 7/7 | expression-plugins +1 |
| add-frame-utilities | Archived | 3/3 | frame-utilities +4 |
| add-frame-utilities-0-6 | Archived | 3/3 | frame-utilities +7 |
| add-frame-verbs | Archived | 13/13 | frame-verbs +6native-bridge ~1 |
| add-horizontal-and-ranges | Archived | 4/4 | horizontal-functions +3 |
| add-html-tables | Archived | 6/6 | dataframe-api +1native-bridge +1 |
| add-inspection-and-config | Archived | 6/6 | inspection +4 |
| add-joins-and-concat | Archived | 10/10 | api-conventions +2combining-frames +3data-types ~2native-bridge ~1 |
| add-json-io | Archived | 3/3 | json-io +3 |
| add-list-namespace | Archived | 3/3 | list-functions +4 |
| add-nested-dtypes | Archived | 5/5 | data-types ~1nested-data +4 |
| add-nested-strings | Archived | 3/3 | strings +3 |
| add-nim-callbacks | Archived | 3/3 | callbacks +4 |
| add-openspec-page | Archived | 4/4 | ci ~2dev-log +1 |
| add-parameter-type-convention | Archived | 1/1 | api-conventions +1 |
| add-parquet-ipc | Archived | 7/7 | csv-io +1native-bridge ~1parquet-ipc +4 |
| add-plan-serialization | Archived | 3/3 | plan-serialization +3 |
| add-polars-coverage-page | Archived | 3/3 | dev-log +1 |
| add-repeat-by-and-seeds | Archived | 3/3 | list-functions +2 |
| add-reshaping | Archived | 4/4 | reshaping +5 |
| add-review-mode | Archived | 6/6 | dev-log +2 |
| add-rolling-and-ewm | Archived | 5/5 | missing-values +1rolling-windows +3 |
| add-row-objects | Archived | 3/3 | row-objects +2 |
| add-sample-datasets | Archived | 5/5 | datasets +3 |
| add-series-api | Archived | 4/4 | series +4 |
| add-spec-examples | Archived | 7/7 | ci ~2spec-examples +3 |
| add-specview-full-specs | Archived | 3/3 | spec-review +2 |
| add-sql | Archived | 3/3 | sql +3 |
| add-streaming-and-sinks | Archived | 3/3 | streaming +4 |
| add-string-expressions | Archived | 7/7 | native-bridge ~1strings +6 |
| add-struct-namespace | Archived | 3/3 | struct-functions +5 |
| add-temporal-types | Archived | 10/10 | csv-io ~1data-types ~3native-bridge ~1temporal +7 |
| add-testing-helpers | Archived | 2/2 | testing-helpers +2 |
| add-top-k-rows-and-date-parts | Archived | 10/10 | dataframe-api ~1inspection ~2temporal +1temporal-grouping ~1value-functions +1 |
| add-typed-errors | Archived | 7/7 | combining-frames ~3csv-io ~1data-types ~1dataframe-api +1 ~2 −1datamancer-interop ~1frame-verbs ~3inspection ~1missing-values ~1native-bridge ~2 |
| add-value-functions | Archived | 6/6 | value-functions +6 |
| build-lib-with-nightly | Archived | 5/5 | binary-distribution +1strings +1 |
| one-program-builds | Archived | 7/7 | ci +1 ~1spec-examples ~1 |
| pin-polars-to-py-release | Archived | 3/3 | categoricals ~1native-bridge +1streaming −1 |
| print-dtypes-as-nanuq-code | Archived | 3/3 | data-types ~2nested-data ~1 |
| refine-book-needs-0-6 | Archived | 3/3 | excel-io ~1temporal-grouping +1 |
| ship-prebuilt-binaries | Archived | 11/11 | binary-distribution +6ci +1 ~1native-bridge +1 ~1 |
| use-how-for-method-params | Archived | 3/3 | api-conventions +1expressions ~1horizontal-functions ~1missing-values ~1 |
No active changes.
add-api-polish Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 11/11
- Archive
Proposal
Why
The 0.3 explainer ("Aged 19") and the Nanuq Book ports keep tripping over small things in the 0.2 API: toSeq clashes with sequtils.toSeq, col("a") / col("b") silently truncates integers, every tiny frame repeats series(...) for each column, col("race") is noisy next to Python's pl.col.race, there is no way to count nulls inside a query, and shared places in a ranking need rank. None of them is big, and all of them change how the rest of 0.3 reads, so they land first.
This change takes up the BACKLOG.md entries "Block syntax for building a dataframe", "/ on two integer columns: open design question" and "toSeq clashes with sequtils.toSeq". It is the first change of the 0.3 release. The API choices were made by Pietro on 2026-10-31 in the 0.3 design discussion (dev log "Designing Nanuq 0.3", section 7, and the decisions that followed it): true division for / because Nim's / is closer to Python than to Rust, col.name shorthand, string keys and nil in the block syntax, Expr.nullCount, and rank with ties.
What Changes
- BREAKING:
toSeqis renamedtoList(Polars'to_list), for plain andOptiontypes.toSeq(walkFiles("*.csv"))compiles again with Nanuq imported. - BREAKING:
/is true division.col("a") / col("b")on integers gives f64, as in Python Polars and Nim (7 / 2 == 3.5); a division by zero givesinforNaN.divstays Polars' floor division. col.nameshorthand:col.raceiscol("race"), as Python'spl.col.race.colbecomes a constant whose call operator keeps every existing form working:col("a"),col("a", "b"),col(SomeNumber),col(float, int).- Block syntax for
newDataFrame:
let df = newDataFrame:
rider: ["Pogačar", "Seixas"]
wins: [22, nil] # nil is a missing value
"nrs + 5": [1, 2] # string keys for names that aren't identifiers
Each line becomes series(name, values). A bracket holding nil becomes an Option column typed from its other values. newDataFrame() with no columns stays valid.
Expr.nullCount: the number of nulls as an aggregation,col.a.nullCount.rank(rankMethod = Average, descending = false, seed = none(int))with a pure enumRankMethod(Average,Min,Max,Dense,Ordinal,Random). Written positionally,rank(Min, descending = true), becausemethodis a Nim keyword.- Polars feature
rankis compiled in. The crate version becomes0.3.0-dev.
Capabilities
New Capabilities
None.
Modified Capabilities
dataframe-api:toList, the block syntax, thecol.nameshorthand and true division.missing-values:toListin the null reads, andExpr.nullCount.data-types:toListin the casting scenario.frame-verbs:toListin the row window example.expressions:rankandRankMethod.native-bridge:NqRankMethodjoins the enums kept in the same order.
Differences from Polars
Expected differences from Polars' Rust and Python APIs:
/matches Python Polars (truediv), not Rust Polars'/operator, which truncates integer division and gives null for a division by zero. This is the one operator where Nanuq picks Python over Rust, because Nim's own/does the same.col.nameworks for any column name that is a Nim identifier, keywords such asendincluded. A few names are taken by Nim before the shorthand sees them:type, and procs fromsystemthat accept anything, such asreprandsizeof. Those columns needcol("type"). Python'spl.col.namehas similar gaps (methods ofpl.col), different ones.- Block syntax has no Polars counterpart: Python writes a dict (
pl.DataFrame({"a": [...]})), Rust thedf!macro (df!("a" => [...])). Missing values arenilwhere Python writesNone. rank's method is a positional argument: Python's keywordmethod=can't be a Nim named argument becausemethodis a keyword. The parameter is namedrankMethod. The default isAverage, as in Python (Rust has no default).seedapplies only toRandom.toListtakes the Nim element type:df.toList("a", int). Python'sSeries.to_list()infers it.- Names follow Polars in camelCase:
null_count→nullCount,to_list→toList.
Impact
src/rust/src/lib.rs:NqBinOpgainsTrueDivand/maps to it; newnq_expr_rankwithNqRankMethod;NqUnarygainsNullCount.Cargo.tomladds therankfeature and moves to0.3.0-dev.src/nanuq/ffi.nimandsrc/nanuq.nim: the declarations,toList,ColNswith call and dot operators, thenewDataFramemacro,nullCount,rank.src/nanuq/datamancer.nim, tests, README, dev log posts and examples move fromtoSeqtotoList.tests/test_basic.nimandtests/test_expressions.nimcover the new API.
Spec changes
data-types modified
Casting
Unchanged in this spec: DataType values, DataType constants and predicates, Schemas, Nim types map to DataType, Full-range UInt64
dataframe-api modified
Building and reading data
Reading columns by type
Block syntax for building a DataFrame
newDataFrame SHALL accept a block of name: [values] lines and build one column per line, in order, as series(name, values) would. A name SHALL be a Nim identifier or a string literal. A nil inside the brackets SHALL be a missing value, and the column SHALL then have the type of its other values. newDataFrame SHALL keep accepting series (newDataFrame(series(...), ...), a seq of series, or none at all).
let df = newDataFrame:
rider: ["Pogačar", "Seixas", "Vingegaard"]
wins: [22, 8, nil]
"win %": [0.31, 0.12, 0.05]
echo df
shape: (3, 3)
┌────────────┬──────┬───────┐
│ rider ┆ wins ┆ win % │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ f64 │
╞════════════╪══════╪═══════╡
│ Pogačar ┆ 22 ┆ 0.31 │
│ Seixas ┆ 8 ┆ 0.12 │
│ Vingegaard ┆ null ┆ 0.05 │
└────────────┴──────┴───────┘
- WHEN a frame is built with the block syntax and the same frame with
seriescalls - THEN both have the same columns, dtypes and values
- WHEN a line reads
wins: [22, nil] - THEN column "wins" is i64 with values 22 and null
- WHEN a line reads
wins: [nil, nil] - THEN the program fails to compile
- WHEN
newDataFrame()is called - THEN the result has shape (0, 0)
Column shorthand
col.name SHALL be the same expression as col("name") for any column name that is a Nim identifier and not taken by Nim first (type, and generic system procs such as repr). Every other form of col SHALL keep working: col("a"), col("a", "b"), col(SomeNumber) and col(float, int). User code SHALL need no pragma to use them.
let df = newDataFrame:
race: ["Sanremo", "Lombardia"]
"end": [1, 2]
echo df.select(col.race, col.end, col("race", "end").count.name.suffix("_n"))
shape: (2, 4)
┌───────────┬─────┬────────┬───────┐
│ race ┆ end ┆ race_n ┆ end_n │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ u32 ┆ u32 │
╞═══════════╪═════╪════════╪═══════╡
│ Sanremo ┆ 1 ┆ 2 ┆ 2 │
│ Lombardia ┆ 2 ┆ 2 ┆ 2 │
└───────────┴─────┴────────┴───────┘
- WHEN
$col.raceand$col("race")are compared - THEN they are equal
- WHEN
col.lenandcol.minare used - THEN they select the columns "len" and "min"
True division
/ on expressions SHALL be Polars' true division: the result SHALL be a float column even when both sides are integers, and a division by zero SHALL give inf or NaN, not null. div SHALL stay floor division.
let df = newDataFrame:
seconds: [7200, 5400, 0]
echo df.select(col.seconds, (col.seconds / 3600).alias("hours"),
(col.seconds div 3600).alias("whole"), (col.seconds / 0).alias("by_zero"))
shape: (3, 4)
┌─────────┬───────┬───────┬─────────┐
│ seconds ┆ hours ┆ whole ┆ by_zero │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ i64 ┆ f64 │
╞═════════╪═══════╪═══════╪═════════╡
│ 7200 ┆ 2.0 ┆ 2 ┆ inf │
│ 5400 ┆ 1.5 ┆ 1 ┆ inf │
│ 0 ┆ 0.0 ┆ 0 ┆ NaN │
└─────────┴───────┴───────┴─────────┘
- WHEN
lit(7) / 2is evaluated - THEN the result is 3.5 with dtype f64
- WHEN
lit(7) div 2is evaluated - THEN the result is 3 with dtype i64
Unchanged in this spec: Automatic memory management, Expressions and lazy queries, HTML tables, Errors as PolarsError
expressions modified
Ranking
Expr SHALL support rank(rankMethod = Average, descending = false, seed = none(int)) with a pure enum RankMethod (Average, Min, Max, Dense, Ordinal, Random), giving each value its rank from 1. Ties SHALL be handled as Polars does: Average gives tied values the mean of their ranks (f64), Min and Max the lowest or highest (u32), Dense leaves no gaps after ties, and Ordinal breaks ties by position. seed SHALL make Random repeatable. Nulls SHALL stay null.
let roll = newDataFrame:
rider: ["Merckx", "Pogačar", "De Vlaeminck", "Van Looy", "Kelly"]
monuments: [19, 13, 11, 8, 9]
echo roll.select(col.rider, col.monuments,
col.monuments.rank(Min, descending = true).alias("place"),
col.monuments.rank.alias("avg"))
shape: (5, 4)
┌──────────────┬───────────┬───────┬─────┐
│ rider ┆ monuments ┆ place ┆ avg │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ u32 ┆ f64 │
╞══════════════╪═══════════╪═══════╪═════╡
│ Merckx ┆ 19 ┆ 1 ┆ 5.0 │
│ Pogačar ┆ 13 ┆ 2 ┆ 4.0 │
│ De Vlaeminck ┆ 11 ┆ 3 ┆ 3.0 │
│ Van Looy ┆ 8 ┆ 5 ┆ 1.0 │
│ Kelly ┆ 9 ┆ 4 ┆ 2.0 │
└──────────────┴───────────┴───────┴─────┘
- WHEN
rank(Min, descending = true)runs over 9, 9, 7 - THEN the result is 1, 1, 3
- WHEN
rank(Dense)runs over 9, 9, 7 - THEN the result is 2, 2, 1
- WHEN
rank()runs over 9, 9, 7 - THEN the result is 2.5, 2.5, 1.0 with dtype f64
Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Filtering inside expressions, Shape and position aggregations, Boolean aggregations, Entropy, Row count expression, Several window keys and selector concatenation, Null-aware comparisons and closeness, More expression functions
frame-verbs modified
Row windows
Unchanged in this spec: Dropping and renaming columns, Unique rows, Row index, Sorting by several keys, Sampling rows, Every n-th row, Frame interpolation, Casting by data type, Several filter predicates, Group order parameter, Frame aggregations, Group-by shortcuts, Iterating over groups, Frame fillNan and select without a frame
missing-values modified
Nulls are read as Option
Plain reads refuse nulls
Inspecting nulls
Null expressions
Unchanged in this spec: Building columns with nulls, CSV null markers, Dropping rows with nulls, Interpolation, Null literal, Filling nulls in whole frames
native-bridge modified
Nim declarations mirror the C ABI
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release
Design
Design
Context
col is a proc today, plus a macro (col(SomeNumber)) and a proc with two or more names returning a Selector. Python Polars' pl.col is an object with a __call__ and a __getattr__, so pl.col("a") and pl.col.a both work. newDataFrame is a proc over varargs[Series]. Polars 0.55 has Expr::true_div, Expr::null_count and Expr::rank(RankOptions { method, descending }, seed) (feature rank).
Decisions
col is a constant with call and dot operators
const col* = ColNs() with () overloads for every existing form (one name, several names, the type selector macro), and a . template that turns col.race into col("race"). The experimental callOperator and dotOperators features only need to be enabled where the operators are declared, so user code needs no pragma (checked with Nim 2.2.4). The dot template only fires when nothing else matches, so col.len is a column but col.repr is system.repr.
Alternative considered: a col macro taking an untyped dot expression. It can't tell col.a from col(a) where a is a variable, and macros can't be overloaded on untyped arguments cleanly.
newDataFrame is a macro over varargs[untyped]
A macro with one untyped parameter and a proc over varargs[Series] don't overload: the block form gets sem-checked against the proc and fails. So newDataFrame becomes a single macro. With one block argument it rewrites each name: [values] line to series("name", values); with anything else it forwards the arguments unchanged to the old proc (now private), so newDataFrame(series(...), series(...)), newDataFrame(someSeq) and newDataFrame() keep working.
nil inside a bracket turns the bracket into [some(a), none(typeof(a)), ...], with the type taken from the first non-nil value. A bracket of only nil fails to compile: there is no type to infer.
True division through NqBinOp
NqBinOp.Div now maps to Expr::true_div. Rust's truncating / is not exposed (div already gives floor division, which is what integer code wants). No new ABI function.
rank
nq_expr_rank(e, NqRankMethod, descending, has_seed, seed). Polars returns f64 for Average and u32 otherwise; Nanuq passes that through.
Risks / Trade-offs
colas a constant: code that tookcolas a proc value (names.map(col)) breaks;names.mapIt(col(it))works. Nothing in the repo does that.- Changing
/silently changes results of 0.2 code. Nanuq has no users yet, and the CHANGELOG says so under "Changed".
Tasks
1. Bridge
- 1.1Add the Polars feature
rankand move the crate to0.3.0-dev - 1.2Map
NqBinOp::Divtotrue_div; addNqUnary::NullCount - 1.3Add
nq_expr_rankwithNqRankMethod - 1.4Mirror everything in
ffi.nim; verify thatcargo build --releasepasses
2. Nim API
- 2.1Rename
toSeqtotoListeverywhere (library, Datamancer module, tests, README, dev log posts, examples) - 2.2Turn
colinto aColNsconstant with call operators for every existing form and a dot template - 2.3Turn
newDataFrameinto a macro with the block syntax (nilas missing, string keys) that forwards other calls to the series form - 2.4Add
Expr.nullCountandrankwithRankMethod - 2.5Tests:
toSeq(walkFiles(...))compiles with Nanuq imported,col.namegives the same plan ascol("name"), the block syntax (nil, string keys, compile failure for only nil), true division and division by zero,nullCountinagg, everyRankMethod
3. Docs and integration
- 3.1README:
toList,col.name, the block syntax and true division; verify thatnimble test,nimble exampleandnimble specexamplespass - 3.2Archive the change: remove the three BACKLOG entries, add CHANGELOG lines (Changed for
/andtoList), update spec example outputs with--update
Revisions
b925875 Implement and archive add-api-polishFirst version: design.md, proposal.md, specs/data-types/spec.md, specs/dataframe-api/spec.md, specs/expressions/spec.md, specs/frame-verbs/spec.md, specs/missing-values/spec.md, specs/native-bridge/spec.md, tasks.md
add-arraymancer-interop Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
Numerical work in Nim (linear algebra, statistics, machine learning with Flambeau or Arraymancer's own layers) happens on Arraymancer tensors, the way Python moves from Polars to NumPy with to_numpy. BACKLOG.md lists "Arraymancer tensors (S): copy numeric columns to and from Tensor[T]", and the coverage map puts it in 0.4.
It is the ninth change of the 0.4 release, from the BACKLOG.md entry "Arraymancer tensors".
What Changes
- An optional module
nanuq/arraymancer, likenanuq/datamancer: only it imports Arraymancer. toTensor(series, T),toTensor(df, column, T)andtoTensor(df, T, columns)(a 2-D tensor, one row per row), for T in int, float and bool; nulls become NaN in float tensors and raiseInvalidOperationErrorotherwise.toSeries(tensor, name)for 1-D tensors andtoDataFrame(tensor, columns)for 2-D tensors.- CI already installs Datamancer, which depends on Arraymancer, so the new test runs there.
Capabilities
New Capabilities
arraymancer-interop: copying numeric columns to and from Arraymancer tensors.
Differences from Polars
- Python's
to_numpycan be zero-copy; Nanuq copies (zero-copy needs the Arrow C Data Interface, a backlog item). - The element type is given (
toTensor(float)); Python infers the NumPy dtype. toDataFrametakes a 2-D tensor only (Python'sfrom_numpyalso takes 1-D arrays and anorient).
Impact
- New
src/nanuq/arraymancer.nimandtests/test_arraymancer.nim;nanuq.nimbletest list; a comment in.github/workflows/ci.yml; BACKLOG.md entry removed.
Spec changes
arraymancer-interop modified
Columns to tensors
The optional module nanuq/arraymancer SHALL provide toTensor(series, T), toTensor(df, column, T) and toTensor(df, T, columns), copying values into an Arraymancer Tensor[T] for T in int, float and bool; the frame version SHALL give a 2-D tensor with one row per row of the frame. Nulls SHALL become NaN in float tensors and SHALL raise InvalidOperationError for int and bool.
import pkg/arraymancer, nanuq/arraymancer
let df = newDataFrame:
oni: [2.4, 2.6, 2.0]
temp: [14.7, 15.0, 15.2]
let t = df.toTensor(float)
echo t.shape[0], "x", t.shape[1], " ", t[1, 0]
TBD
- WHEN a float column with a null is copied with
toTensor("a", float) - THEN the tensor holds NaN at that position
Tensors to columns
toSeries(tensor, name) SHALL copy a 1-D tensor into a Series, and toDataFrame(tensor, columns) SHALL copy a 2-D tensor into a frame with one column per tensor column, named columns or column_0, column_1, ...
import pkg/arraymancer, nanuq/arraymancer
echo [[1.0, 2.0], [3.0, 4.0]].toTensor.toDataFrame(["a", "b"])
TBD
- WHEN
toSeriesis called on a 2-D tensor - THEN
ValueErroris raised
Tasks
1. Implementation
- 1.1
nanuq/arraymancerwithtoTensor,toSeries,toDataFrame - 1.2Tests in
tests/test_arraymancer.nim, run bynimble testand CI - 1.3BACKLOG.md entry removed; CHANGELOG
Revisions
46ae6c2 Nanuq 0.4, changes 8-10: Series API, Arraymancer tensors, row objectsFirst version: proposal.md, specs/arraymancer-interop/spec.md, tasks.md
add-arrow-c-data Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
The Arrow C Data Interface is the standard way to hand columns between libraries in one process without copying: DuckDB, Arrow C++/GLib, nanoarrow and any Arrow-aware C library read and write it. It is how Python Polars talks to PyArrow, pandas and DuckDB (to_arrow, from_arrow, __arrow_c_stream__), and the 0.6 book map counts 7 sections using it. It also gives Nim code zero-copy access to Polars' buffers, which is what the BACKLOG.md entry "Zero-copy columns through the Arrow C Data Interface" asks for, to make mapElements faster.
It is the fourth change of the 0.6 release and takes that BACKLOG.md entry.
What Changes
- Nim objects with the standard layouts:
ArrowSchema,ArrowArray,ArrowArrayStream, andreleasefor each. s.toArrow: ArrowExport(schema + array, released when it goes away unless a consumer took them over) andfromArrow(schema, array, name)/fromArrow(export)for Series;df.toArrow: ArrowArrayStreamandfromArrow(stream)for frames (record batches as struct arrays).s.view(T)/df.view(column, T): aColumnView[T]reading a numeric column without nulls in place (v[i],v.len,items,v.toOpenArray).mapElementson numeric columns without nulls reads each batch through a view instead of copying it into a seq first.
Capabilities
New Capabilities
arrow-interop: exchanging columns and frames through the Arrow C Data Interface, and zero-copy views.
Differences from Polars
- Python returns PyArrow objects (
pa.Array,pa.Table); Nanuq hands out the C structs themselves, which is what a Nim program passes to a C library. There is nocompat_levelargument: Nanuq always exports the newest layout (string views). fromArrowtakes over the array (Arrow's move semantics); Python copies or shares through PyArrow.viewhas no Python counterpart besidesto_numpy(allow_copy = False), which it mirrors for numeric columns; it refuses columns with nulls instead of copying.
Impact
src/rust/Cargo.toml:polars-arrow(for itsffimodule).src/rust/src/lib.rs,src/nanuq/ffi.nim:nq_series_to_arrow,nq_series_from_arrow,nq_df_to_arrow_stream,nq_df_from_arrow_stream, and the struct layouts.src/nanuq.nim: the API above and themapElementsfast path.- New
tests/test_arrow.nim;benchmarks/map_elementsrerun.
Spec changes
arrow-interop modified
Series through the Arrow C Data Interface
s.toArrow SHALL export a Series as an ArrowExport holding the standard ArrowSchema and ArrowArray C structs, without copying the values. Whatever a consumer did not take over SHALL be released when the export goes away. fromArrow(schema, array, name = "") SHALL import a Series from such structs, taking over the array.
var ex = series("kg", @[410, 380]).toArrow
echo ex.schema.format, " ", ex.array.length
let back = fromArrow(ex, name = "mass")
echo back
TBD
- WHEN an export's array is imported with
fromArrow - THEN the export's
array.releaseis nil and the Series reads the same values
Frames through the Arrow C stream interface
df.toArrow SHALL export a frame as an ArrowArrayStream of record batches (struct arrays), and fromArrow(stream) SHALL read a whole stream into a frame and release it.
let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.0, 380.5]))
var stream = df.toArrow
echo fromArrow(stream)
TBD
- WHEN a frame with List, Struct and Datetime columns goes through
toArrowandfromArrow - THEN the result equals the frame
Zero-copy views
s.view(T) and df.view(column, T) SHALL give a ColumnView[T] over a numeric column's values without copying, with [], len, items and toOpenArray. T SHALL match the column's type exactly and the column SHALL have no nulls, else InvalidOperationError.
import std/math
let df = newDataFrame(series("kg", @[410.0, 380.5, 455.0]))
let v = df.view("kg", float)
echo v.len, " ", v[1], " ", sum(v.toOpenArray)
TBD
- WHEN an Int64 column is viewed as
float - THEN
InvalidOperationErroris raised
- WHEN a column with a null is viewed
- THEN
InvalidOperationErroris raised
Tasks
1. Implementation
- 1.1Crate: polars-arrow ffi; Series export/import; frame stream export/import
- 1.2Nim struct layouts,
toArrow,fromArrow,ArrowExport,ColumnView,view; mapElements fast path - 1.3Tests in
tests/test_arrow.nim; benchmark rerun;nimble testandnimble specexamplespass; CHANGELOG; BACKLOG entry removed
Revisions
4ea5dad 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6First version: proposal.md, specs/arrow-interop/spec.md, tasks.md
add-binary-decimal-bitwise Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
Binary and Decimal are the two Polars data types Nanuq still shows as Other. Decimal matters for money and for data read from databases and Parquet files that store exact numbers; Binary for raw bytes (hashes, images, encoded payloads) and is the one blocker of the user guide's lazy/gpu page. Bitwise operations come with them in the roadmap's 0.6 line "Binary, Decimal dtypes; bitwise ops". It takes the BACKLOG.md entry "More dtypes".
It is the third change of the 0.6 release.
What Changes
DataTypeKindgainsBinaryandDecimal; constantsBinaryandDecimal(precision = 38, scale = 0); tables printbinaryanddecimal[p,s],$printsBinaryandDecimal(p, s).series(name, strings, dtype): withBinarythe strings are raw bytes (any bytes); other dtypes cast the strings (Decimal(5, 2)parses them).- Reading back: Binary columns read as
string(raw bytes); Decimal columns asstring(exact) orfloat. binnamespace:contains,startsWith,endsWith,encode(Hex | Base64),decode(Hex | Base64),size(unit).str.encode(Hex | Base64),str.toDecimal(scale).- Bitwise expressions:
bitwiseCountOnes,bitwiseCountZeros,bitwiseLeadingOnes,bitwiseLeadingZeros,bitwiseTrailingOnes,bitwiseTrailingZeros, and the aggregationsbitwiseAnd,bitwiseOr,bitwiseXor. (and,or,xorbetween integer expressions already work bitwise, as in Polars.)
Capabilities
New Capabilities
binary-decimal: Binary and Decimal data and their functions, bitwise operations.
Differences from Polars
- Nim has no
bytestype: Binary values are Nim strings holding raw bytes, built withseries(name, strings, Binary)(Pythonpl.Series([b"..."])). - Nim has no decimal type in the standard library: Decimal values are read as strings (exact) or floats, and written from strings (Python uses
decimal.Decimal). encode/decodetake aBinaryEncodingenum (Python"hex"/"base64"strings);decodeis always strict.str.toDecimaltakes thescale; Python 2.x infers it from the first rows (inference_length).
Impact
src/rust/Cargo.toml: Polars featuresbinary_encoding,bitwise,string_encoding.src/rust/src/lib.rs,src/nanuq/ffi.nim: dtype codes,nq_dtype_decimal,nq_series_new_binary,nq_expr_bin,nq_expr_str_codec,nq_expr_bitwise; string reads accept Binary columns, float reads Decimal ones.- New
tests/test_binary_decimal.nim.
Spec changes
binary-decimal modified
Binary data
Binary SHALL be a data type of raw bytes. series(name, strings, Binary) SHALL build a Binary column whose values are the strings' bytes (any bytes), and toList(column, string) SHALL read them back unchanged.
let s = series("sig", ["\x00\xff", "bear"], Binary)
echo s.dtype
let df = newDataFrame(s)
echo df
echo df.toList("sig", string) == @["\x00\xff", "bear"]
TBD
- WHEN a String column is cast to
Binary - THEN its values read back as the same strings
Decimal data
Decimal(precision = 38, scale = 0) SHALL be the exact decimal type, with precision 1 to 38 and scale 0 to precision (else ValueError). Strings SHALL become decimals with series(name, strings, Decimal(p, s)) or str.toDecimal(scale), and Decimal columns SHALL read back as string (exact) or float.
let df = newDataFrame(series("price", ["1.25", "10.50", "0.10"], Decimal(10, 2)))
echo df
echo df.select(col("price").sum)
echo df.toList("price", float)
TBD
- WHEN
Decimal(40, 2)is called - THEN
ValueErroris raised
Binary functions
e.bin SHALL provide contains, startsWith, endsWith (with a string of bytes or an expression), encode(BinaryEncoding) (hex or base64 text), decode(BinaryEncoding) and size(unit = SizeUnit.Bytes); str.encode(BinaryEncoding) SHALL encode strings' UTF-8 bytes.
let df = newDataFrame(series("b", ["bear", "cub"], Binary))
echo df.select(col("b").bin.encode(BinaryEncoding.Hex).alias("hex"),
col("b").bin.startsWith("be").alias("be"), col("b").bin.size.alias("n"))
echo newDataFrame(series("s", @["hi"])).select(col("s").str.encode(BinaryEncoding.Base64))
TBD
- WHEN a Binary column is encoded to hex, cast to Binary and decoded from hex
- THEN the values equal the original
Bitwise operations
Integer expressions SHALL provide bitwiseCountOnes, bitwiseCountZeros, bitwiseLeadingOnes, bitwiseLeadingZeros, bitwiseTrailingOnes, bitwiseTrailingZeros (per value) and bitwiseAnd, bitwiseOr, bitwiseXor (aggregations).
let df = newDataFrame(series("flags", @[0b0110'u8, 0b0011'u8]))
echo df.select(col("flags").bitwiseCountOnes.alias("ones"),
col("flags").bitwiseTrailingZeros.alias("tz"))
echo df.select(col("flags").bitwiseAnd.alias("and"), col("flags").bitwiseOr.alias("or"))
TBD
- WHEN
bitwiseCountOnesis applied to a String column - THEN
PolarsErroris raised
Unchanged in this spec: Binary slicing and bytes, Strings to integers
Tasks
1. Implementation
- 1.1Crate: features; Binary/Decimal dtype codes, constructors, reads; bin, str codec, bitwise
- 1.2
Binary,Decimal,series(..., dtype),bin.*,str.encode,str.toDecimal,bitwise* - 1.3Tests in
tests/test_binary_decimal.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
4ea5dad 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6First version: proposal.md, specs/binary-decimal/spec.md, tasks.md
add-book-port-needs Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 7/7
- Archive
Proposal
Why
Porting the Nanuq Book chapters to 0.4 (nanuq-book#6) worked, and every Nim frame matched Python, but the port worked around a few gaps that are small to close: any/all aggregations (the book used min/max on booleans), a null literal (fill_nan(None)), groupBy with column names, and frame gatherEvery. It also found that eager df.groupBy(...).agg(...) returned a LazyFrame, unlike Python.
It is the thirteenth change of the 0.4 release (#51). The larger items from the same list go to BACKLOG.md.
What Changes
Expr.any(ignoreNulls)andExpr.all(ignoreNulls)aggregations (also on Series).lit(nil)null literal andfillNan(nil).groupBy("a", "b")andselect("a", "b")with column names, on DataFrame and LazyFrame (select from the explainer port).gatherEvery(n, offset)on DataFrame and LazyFrame.- BREAKING On a DataFrame,
groupBy,groupByDynamicandrollingreturn aGroupBywhoseaggreturns a DataFrame, as in Python (it returned a LazyFrame, so eager code needed.collect). LazyFrame keepsLazyGroupBy.
Capabilities
Modified Capabilities
expressions: boolean aggregations.missing-values: null literal.dataframe-api:groupByby name; eageraggreturns a DataFrame.frame-verbs: every n-th row.
Differences from Polars
- Python writes
pl.lit(None)andfill_nan(None); Nanuq writeslit(nil)andfillNan(nil). anyandallon a Series return a one-value Series (s.all.item(bool)), as other Series aggregations do; Python returns a bool.all()with no argument stays the column selector, as Python'spl.all().
Impact
- Rust:
nq_expr_lit_null,nq_expr_any_all. src/nanuq.nim:lit(nil),fillNan(nil),any,all,groupBy(varargs[string]), framegatherEvery, theGroupBytype.- Tests in
tests/test_expressions.nim,tests/test_nulls.nim,tests/test_verbs.nim.
Spec changes
dataframe-api modified
Expressions and lazy queries
Unchanged in this spec: Automatic memory management, Building and reading data, Reading columns by type, HTML tables, Block syntax for building a DataFrame, Column shorthand, True division, Errors as PolarsError
expressions modified
Boolean aggregations
Expr SHALL support any(ignoreNulls = true) and all(ignoreNulls = true) on boolean columns, as aggregations: whether any value, or every value, is true. With ignoreNulls = false they SHALL follow Kleene logic: any is null when there are nulls and no true value, all is null when there are nulls and no false value. The all() selector (no arguments) SHALL keep working.
let df = newDataFrame:
team: ["a", "a", "b", "b"]
won: [true, false, true, true]
echo df.groupBy("team").agg(col.won.all.alias("always"), col.won.any.alias("ever"))
- WHEN
any(ignoreNulls = false)runs on false and null - THEN the result is null
Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Ranking, Filtering inside expressions, Shape and position aggregations, Entropy, Row count expression, Several window keys and selector concatenation, Null-aware comparisons and closeness, More expression functions
frame-verbs modified
Every n-th row
LazyFrame and DataFrame SHALL support gatherEvery(n, offset = 0), keeping rows offset, offset + n, offset + 2n, ... (Python's gather_every).
let df = newDataFrame:
month: [1, 2, 3, 4, 5, 6]
echo df.gatherEvery(3, offset = 2)
- WHEN
gatherEvery(2, offset = 10)runs on 6 rows - THEN the result has no rows
Unchanged in this spec: Dropping and renaming columns, Row windows, Unique rows, Row index, Sorting by several keys, Sampling rows, Frame interpolation, Casting by data type, Several filter predicates, Group order parameter, Frame aggregations, Group-by shortcuts, Iterating over groups, Frame fillNan and select without a frame
missing-values modified
Null literal
lit(nil) SHALL be a null literal (Python's pl.lit(None)), usable wherever an expression is, and fillNan(nil) SHALL turn NaN values into nulls.
let df = newDataFrame:
x: [1.0, NaN, 3.0]
echo df.select(col.x.fillNan(nil).alias("x"), col.x.fillNan(nil).nullCount.alias("nulls"))
- WHEN
select(lit(nil).alias("n"))runs with another column of 3 rows - THEN
nholds 3 nulls
Unchanged in this spec: Nulls are read as Option, Plain reads refuse nulls, Inspecting nulls, Building columns with nulls, CSV null markers, Null expressions, Dropping rows with nulls, Interpolation, Filling nulls in whole frames
Tasks
1. Implementation
- 1.1
nq_expr_lit_null,nq_expr_any_all - 1.2
lit(nil),fillNan(nil),any,all(Expr and Series) - 1.3
groupByby column names - 1.4Frame
gatherEvery - 1.5Eager
GroupBywhoseaggreturns a DataFrame; callers drop.collect - 1.6Tests
- 1.7The rest of the book's list goes to BACKLOG.md
Revisions
dd3c102 any/all, lit(nil), groupBy by name, frame gatherEvery; eager agg returns a DataFrameFirst version: proposal.md, specs/dataframe-api/spec.md, specs/expressions/spec.md, specs/frame-verbs/spec.md, specs/missing-values/spec.md, tasks.md
22cc54c select("a", "b") with column namesproposal.mdspecs/dataframe-api/spec.mdadd-book-port-needs-0-5 Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 6/6
- Archive
Proposal
Why
Porting the Nanuq Book chapters to 0.5 (about twelve chapters, against this PR) showed that nested display matches Python, and that list.eval, struct.field, explode, concatList, valueCounts and str.split work as written. It also found gaps that the port had to work around: Series had no struct/list namespaces and no HTML for notebooks, entropy and pl.len() were missing, sized integers (int32) did not build columns, and a few frame calls (interpolate, cast by data type, explode("a", "b"), pl.struct("a", "b")) had no Nanuq spelling.
It is the ninth change of the 0.5 release (#53).
What Changes
- Series namespaces
s.list,s.arr,s.struct,s.str,s.dt,s.cat, with every function of the Expr namespace of the same name. toHtml(Series), the HTML Python shows for a Series (shape(n,)), so nimib'snbShow-style helpers work on a Series.Expr.entropy(base = E, normalize = true).len(), the row count expression (Python'spl.len()).- Columns from
int8...uint64andfloat32values (top level, in lists and arrays, innewDataFrame), andtoListfor those types. asStruct("a", "b")with column names.interpolate()on DataFrame and LazyFrame.cast({Float64: Float32})andcast({col(SomeNumber): Float32})on frames.explode("a", "b")with several column names.
Capabilities
Modified Capabilities
series: namespaces, HTML, sized numbers.expressions: entropy, row count.struct-functions: structs from column names.frame-verbs: frame interpolation, casting by data type.list-functions: exploding several columns by name.
Differences from Polars
- Python's Series namespaces are separate classes; in Nanuq
s.list.lenrunscol(s.name).list.lenon a one-column frame (a macro forwards the call), so every Expr namespace function works on a Series, but each call is one small query. len()needs the parentheses: plainlenis Nim's length proc.castkeys are either all data types or all selectors in one call (a Nim table literal has one key type); Python mixes names, types and selectors in one dict.- Selectors are Nanuq's
col(SomeNumber)(Pythoncs.numeric()). uint64values abovehigh(int64)cannot build a column (they go throughint).
Impact
- Rust:
nq_expr_entropy,nq_expr_len. src/nanuq.nim: Series namespace types and dot-operator macros,toHtml(Series),entropy,len(), sized-numberseriesandtoList,asStruct(varargs[string]), frameinterpolate,castby type or selector,explode(a, b, ...).- Tests in
tests/test_nested.nim.
Spec changes
expressions modified
Entropy
Expr SHALL support entropy(base = E, normalize = true), an aggregation giving -sum(p * ln(p)) / ln(base), where p are the values (divided by their sum when normalize is true).
let df = newDataFrame:
votes: [@[1, 1, 2], @[5]]
echo df.select(col.votes.list.agg(element().entropy).alias("entropy"))
- WHEN the entropy of a single positive value is computed
- THEN the result is 0.0
Row count expression
len() with no argument SHALL be an expression counting rows, named len (Python's pl.len()); in a group-by it SHALL count the rows of each group.
let df = newDataFrame:
team: ["a", "a", "b"]
echo df.groupBy("team").agg(len())
- WHEN
df.select(len())runs on 4 rows - THEN the result is one row with
len= 4
Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Ranking, Filtering inside expressions, Shape and position aggregations, Boolean aggregations, Several window keys and selector concatenation, Null-aware comparisons and closeness, More expression functions
frame-verbs modified
Frame interpolation
DataFrame and LazyFrame SHALL support interpolate(how = InterpolationMethod.Linear), filling the nulls of every column as Expr.interpolate does (Python's DataFrame.interpolate).
let df = newDataFrame:
day: [1, 2, 3]
temp: [some(-2.0), none(float), some(1.0)]
echo df.interpolate
- WHEN an integer column with a null between 1 and 5 is interpolated
- THEN it becomes a float column holding 1.0, 3.0, 5.0
Casting by data type
DataFrame and LazyFrame cast SHALL also take a mapping from data types, or from selectors, to data types: cast({Float64: Float32}) casts every Float64 column, cast({col(SomeNumber): Float32}) every column the selector picks; other columns are kept.
let df = newDataFrame:
kg: [410.5, 380.0]
cubs: [1, 0]
bear: ["Ada", "Bo"]
echo df.cast({Float64: Float32}).schema
echo df.cast({col(SomeNumber): Float32}).schema
- WHEN
cast({Float64: Float32})runs on a frame with an Int64 column - THEN the Int64 column is unchanged
Unchanged in this spec: Dropping and renaming columns, Row windows, Unique rows, Row index, Sorting by several keys, Sampling rows, Every n-th row, Several filter predicates, Group order parameter, Frame aggregations, Group-by shortcuts, Iterating over groups, Frame fillNan and select without a frame
list-functions modified
Exploding several columns by name
DataFrame and LazyFrame explode SHALL also take several column names as separate arguments: explode("a", "b") is explode(["a", "b"]).
let df = newDataFrame:
peak: ["Mont Blanc", "Monte Rosa"]
huts: [@["Goûter", "Cosmiques"], @["Margherita", "Gnifetti"]]
m: [@[3835, 3613], @[4554, 3647]]
echo df.explode("huts", "m")
- WHEN two list columns with lists of the same lengths are exploded together
- THEN each row holds the matching elements of both
Unchanged in this spec: List aggregations and access, List transforms, Expressions on list elements, Explode and implode, Repeating values into lists, Seeds as plain ints
series modified
Series namespaces
A Series SHALL have the namespaces list, arr, struct, str, dt and cat, each offering every function of the Expr namespace of the same name: s.ns.f(args) SHALL return the Series s.eval(col(s.name).ns.f(args)). The result keeps the name the expression gives (so s.struct.field("x") is named x).
let df = newDataFrame:
p: [(x: 1, y: 2.0), (x: 3, y: 4.0)]
l: [@[1, 2], @[3]]
echo df["p"].struct.field("x")
echo df["l"].list.len
- WHEN
s.str.toUppercaseruns on a String Series holding "ab" and "c" - THEN the result holds "AB" and "C"
Series as HTML
toHtml(s: Series, maxRows = 10) SHALL return the HTML that Python Polars shows for a Series in notebooks: the table of its one column, with the shape written (n,).
let s = series("kg", [410, 380])
echo s.toHtml
- WHEN a Series of 3 values is turned into HTML
- THEN the HTML shows
shape: (3,)
Columns from sized numbers
series, newDataFrame, lists and arrays SHALL accept int8, int16, int32, int64, uint8, uint16, uint32, uint64 and float32 values (and Option of them), giving the Polars type of the same size, and toList SHALL read columns back as those types.
let df = newDataFrame:
rgb: [[255'u8, 0, 0], [0'u8, 128, 255]]
temp: [-1.5'f32, 2.0]
echo df
echo df.toList("temp", float32)
- WHEN
series("a", [1'i32, 2])is built - THEN its data type is Int32 and
toList(int32)gives@[1'i32, 2]
Unchanged in this spec: Getting a Series, Reading a Series, Series operations, Series in frames, Binary functions on a Series
struct-functions modified
Structs from column names
asStruct SHALL also take column names: asStruct("a", "b") is asStruct(col("a"), col("b")) (Python's pl.struct("a", "b")).
let df = newDataFrame:
bear: ["Ada", "Bo"]
kg: [410, 380]
echo df.select(asStruct("bear", "kg").alias("s"))
- WHEN
asStruct("bear", "kg")is selected - THEN the struct has the fields bear and kg
Unchanged in this spec: Building structs, Struct fields, Unnesting frames, Value counts as an expression, Array functions
Tasks
1. Implementation
- 1.1
nq_expr_entropy,nq_expr_len - 1.2Series namespaces (
list,arr,struct,str,dt,cat) andtoHtml(Series) - 1.3
entropy,len() - 1.4Sized numbers in
series,newDataFrameandtoList - 1.5
asStructby name, frameinterpolate,castby data type or selector,explodeby several names - 1.6Tests
Revisions
d6f53fc 0.5: book port needs (add-book-port-needs-0-5)First version: proposal.md, specs/expressions/spec.md, specs/frame-verbs/spec.md, specs/list-functions/spec.md, specs/series/spec.md, specs/struct-functions/spec.md, tasks.md
add-book-port-needs-0-6 Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 4/4
- Archive
Proposal
Why
Porting the chapters 0.5 already unlocks (O'Reilly ch5, ch9, ch13; Packt ch4, ch5; the user guide's aggregation pages), the 0.6 book thread found gaps the planning map could not see, because the names exist on expressions but not on frames or group-bys: frame aggregations (df.sum()), group-by shortcuts (group_by(...).max()), iterating over groups, df.fill_nan, and pl.select without a frame.
It is the tenth change of the 0.6 release.
What Changes
- Frame aggregations on DataFrame and LazyFrame:
sum,mean,median,product,min,max,std(ddof),var(ddof),quantile(q, interpolation),nUnique,count,nullCount(). Columns the aggregation does not apply to give null, as in Python. - Group-by shortcuts on GroupBy and LazyGroupBy:
len(name),count,head(n),tail(n),first,last,sum,mean,median,min,max,nUnique,quantile(q),all(lists). for key, part in df.groupBy(...): the groups in order of appearance.fillNan(value | nil)on DataFrame and LazyFrame (float columns).select(exprs...)without a frame (Pythonpl.select).- Round 2 from the book (O'Reilly ch9, Packt ch4, user guide data types):
- operators on selectors (
all() > 0keeps each column's name, not "literal"); - comparisons with a value on the left are mirrored (
0 < col("a")iscol("a") > 0, nameda), as Python's reflected comparisons do; over("a", "b")with several names;concatStr([all()], sep)with selectors;describeprints datetimes and the mean of dates as Python'sstr(datetime)does (1986-09-04 00:00:00, no.000000).xorcame in add-frame-utilities-0-6.
Capabilities
Modified Capabilities
frame-verbs: frame aggregations, group-by shortcuts, group iteration, framefillNan,selectwithout a frame.column-selectors: operators on selectors, mirrored comparisons.expressions:overwith several names,concatStrwith selectors.inspection:describeprints temporal values as Python.
Differences from Polars
- Iterating a group-by yields the key as
seq[string](the key values as text, inbyorder), where Python yields a tuple of typed values. - Python's
GroupBy.count()is deprecated in favour oflen(); Nanuq keeps both,countnaming its columncount. head,tailand iteration need a plaingroupBy(notgroupByDynamicorrolling), as in Python.- Series aggregations already exist since 0.4 and return a one-value Series (
s.sum.item(float)); Python returns the scalar.
- Nim has no reflected operators, so the mirroring is done by the overloads: arithmetic with a value on the left (
1 + col("a")) is not mirrored and is named "literal", as in Python (__radd__puts the literal first too).
Impact
src/rust/src/lib.rs,src/nanuq/ffi.nim:nq_lf_group_head(group head/tail).src/nanuq.nim: the procs above, the rest in Nim over existing API.- New
tests/test_bookneeds6.nim.
Spec changes
column-selectors modified
Operators on selectors
Arithmetic, comparison and logical operators SHALL accept a selector (all(), col("a", "b"), col(SomeNumber)) on either side, applying to each selected column and keeping its name; a comparison with a value on the left SHALL be mirrored (0 < x is x > 0), so the result keeps the column's name.
let df = newDataFrame(series("a", @[1, -1]), series("b", @[0, 2]))
echo df.select((all() > 0).name.suffix(" > 0"))
echo df.select(0 < col("a"))
TBD
- WHEN
all() * 2is selected - THEN every column is doubled and keeps its name
Unchanged in this spec: Selecting by Nim type, Selecting by name, Excluding columns, Selectors as expressions, Output name suffix and prefix
expressions modified
Several window keys and selector concatenation
over SHALL take several column names as separate arguments, and concatStr SHALL take selectors, expanding them to their columns.
let df = newDataFrame(series("c", @["x", "x", "y"]), series("b", @["p", "p", "q"]))
echo df.select(concatStr([all()], "-").alias("s"), lit(1).sum.over("c", "b").alias("n"))
TBD
- WHEN
col("v").sum.over("c", "b")is selected - THEN each row gets the sum of its (c, b) group
Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Ranking, Filtering inside expressions, Shape and position aggregations, Boolean aggregations, Entropy, Row count expression, Null-aware comparisons and closeness, More expression functions
frame-verbs modified
Frame aggregations
DataFrames and LazyFrames SHALL provide sum, mean, median, product, min, max, std(ddof = 1), var(ddof = 1), quantile(q, interpolation), nUnique, count and nullCount(), each giving one row with the aggregation of every column; columns of a type the aggregation does not apply to (strings for sum) SHALL give null.
let df = newDataFrame(series("bear", @["Ada", "Bo", "Cy"]), series("kg", @[410, 380, 455]))
echo df.sum
echo df.max
echo df.nullCount
TBD
- WHEN
df.lazy.mean.collectruns - THEN it equals
df.mean
Group-by shortcuts
GroupBy and LazyGroupBy SHALL provide len(name = "len"), count, head(n = 5), tail(n = 5), first, last, sum, mean, median, min, max, nUnique, quantile(q) and all, each aggregating every non-key column per group, with groups in order of appearance.
let df = newDataFrame(series("den", @["N", "S", "N"]), series("kg", @[410, 380, 455]))
echo df.groupBy("den").max
echo df.groupBy("den").len
echo df.groupBy("den").head(1)
TBD
- WHEN
headis called on agroupByDynamic - THEN
InvalidOperationErroris raised
Iterating over groups
for key, part in df.groupBy(columns) SHALL yield each group's key values (as strings, in by order) and its rows, groups in order of appearance.
let df = newDataFrame(series("den", @["N", "S", "N"]), series("kg", @[410, 380, 455]))
for key, part in df.groupBy("den"):
echo key, " ", part.height
TBD
- WHEN a frame is grouped by two columns and iterated
- THEN each key holds two values
Frame fillNan and select without a frame
fillNan(value) on DataFrames and LazyFrames SHALL replace NaN in float columns (nil for null), and select(exprs...) SHALL evaluate expressions without a frame.
echo newDataFrame(series("x", @[1.0, NaN])).fillNan(0.0)
echo select(lit(1).alias("one"), intRange(0, 3).alias("i"))
TBD
- WHEN a frame with an integer and a float column gets
fillNan(0.0) - THEN the integer column is unchanged
Unchanged in this spec: Dropping and renaming columns, Row windows, Unique rows, Row index, Sorting by several keys, Sampling rows, Every n-th row, Frame interpolation, Casting by data type, Several filter predicates, Group order parameter
inspection modified
Describe prints temporal values as Python
describe SHALL print Datetime statistics and the mean of a Date column as YYYY-MM-DD HH:MM:SS, with a fraction only when it is not zero.
let df = newDataFrame(series("d", @[date(1986, 9, 1), date(1986, 9, 7)]))
echo df.describe
TBD
- WHEN the mean of 1986-09-01 and 1986-09-07 is described
- THEN it reads
1986-09-04 00:00:00
Unchanged in this spec: glimpse, describe, Display config, Scoped display config, Table formatting options
Tasks
1. Implementation
- 1.1Crate: group head/tail
- 1.2Frame aggregations, group-by shortcuts, group iteration, frame fillNan,
selectwithout a frame - 1.2bRound 2: operators on selectors, mirrored comparisons,
overvarargs,concatStrselectors,describetemporal strings - 1.3Tests in
tests/test_bookneeds6.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
4ea5dad 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6First version: proposal.md, specs/column-selectors/spec.md, specs/expressions/spec.md, specs/frame-verbs/spec.md, specs/inspection/spec.md, tasks.md
add-categoricals Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 8/8
- Archive
Proposal
Why
Many string columns hold a few distinct values: a team, a nationality, a medal, one of the five Monuments. Polars stores them as Categorical (categories found in the data) or Enum (a fixed, ordered set), which is smaller, faster to group and join, and for Enum sorts in a meaningful order. Nim already has the right tool for a fixed set of names, the enum, so Nanuq can map one to the other: the 0.3 explainer uses type Monument = enum to sort races in calendar order.
This change takes up the categoricals part of BACKLOG.md "More dtypes", following the dev log "Designing Nanuq 0.3" (categoricals moved into 0.3 by Pietro on 2026-10-31). It is the seventh change of the 0.3 release.
What Changes
- Data types:
DataTypeKindgainsCategoricalandEnum.Categoricalis aDataTypeconstant; Enum values carry theircategories.$gives Polars' namescatandenum. Enum(["low", "high"])builds an Enum dtype at run time (duplicates raiseValueError).- Nim enums are Polars Enums:
dataType(Medal)is the Enum of$of each value in order, socast(Medal),series("m", [Gold, Silver]), the block form ofnewDataFrame,toList(df, "m", Medal)anddf["m", i, Medal]work,Option-wrapped for nulls. Enum values can be compared with columns (col.medal == Gold) and used inisIn. Reading a value that is not in the Nim enum raisesInvalidOperationError. e.catreturns aCatNameSpace(adistinct Expr) withgetCategories,lenBytes,lenChars,startsWith,endsWithandslice.e.toPhysicalgives the physical values (category indices, days, integers).describereports no min and max for Categorical and Enum columns, as Python does.- The Polars feature
dtype-categorical(already compiled in) is used.
Not in this change: lexical ordering of Categoricals (Categorical("lexical")), local vs global category scopes (StringCache), cat.toLocal, appending to an Enum's categories.
Capabilities
New Capabilities
categoricals: Categorical and Enum columns, Nim enums, and thecatnamespace.
Modified Capabilities
data-types: the two kinds,categories, and Nim enums indataType.native-bridge:NqCatOpjoins the ordered enums.
Differences from Polars
Expected differences from Polars' Rust and Python APIs:
- Nim enums have no Python or Rust counterpart as a dtype; Python accepts a Python
enum.Enumclass aspl.Enum(MyEnum), which is close. Nanuq uses$of each value, so enums with string values (Flanders = "Ronde van Vlaanderen") name their categories freely. Enumis a proc that returns aDataType(Python'spl.Enum([...])class); comparing kinds needsDataTypeKind.Enum.Categoricalalways uses Polars' global categories, as Python's default; there is noorderingargument.- Names follow Polars in camelCase:
get_categories→getCategories,to_physical→toPhysical.
Impact
src/rust/src/lib.rs: the two dtype codes, Enum categories fromNqDtypeSpec,nq_df_column_n_categories,nq_df_column_category,nq_series_castandnq_expr_catwithNqCatOp.src/nanuq/ffi.nim,src/nanuq.nim: the declarations, theDataTypechanges, enum overloads,CatNameSpaceandtoPhysical.tests/test_categorical.nim(new); README; BACKLOG "More dtypes" drops categoricals.
Spec changes
categoricals modified
Nim enums as Enum columns
A Nim enum type SHALL map to a Polars Enum whose categories are $ of its values in order. series, the block form of newDataFrame, cast(T), toList, df[c, i, T], comparisons and isIn SHALL accept the enum type or its values. Reading a value that is not in the enum SHALL raise InvalidOperationError.
type Monument = enum
Sanremo = "Milano-Sanremo", Flanders = "Ronde van Vlaanderen",
Roubaix = "Paris-Roubaix", Liege = "Liège-Bastogne-Liège", Lombardia = "Il Lombardia"
let wins = newDataFrame:
race: ["Il Lombardia", "Milano-Sanremo", "Paris-Roubaix"]
winner: ["Pogačar", "Pogačar", "van der Poel"]
let byRace = wins.withColumns(col.race.cast(Monument)).sort("race")
echo byRace
echo byRace.toList("race", Monument)
echo byRace.filter(col.race == Roubaix).toList("winner", string)
TBD
- WHEN a column of Monument names is cast to
Monumentand sorted - THEN the rows follow the order of the enum, not the alphabet
- WHEN a string that is not a category is cast to
Monumentstrictly - THEN
InvalidOperationErroris raised
Run-time Enum and Categorical
Enum(categories) SHALL build an Enum dtype from strings, raising ValueError on duplicates, and Categorical SHALL be the dtype of strings with categories found in the data. Both SHALL read back as strings.
let df = newDataFrame:
team: ["UAE", "Visma", "UAE"]
level: ["high", "low", "high"]
let t = df.select(col.team.cast(Categorical), col.level.cast(Enum(["low", "high"])))
echo t.schema
echo t.sort("level").toList("level", string)
TBD
- WHEN
dtype(df, c).categoriesis read for a column cast toEnum(["low", "high"]) - THEN it is
@["low", "high"]
The cat namespace
e.cat SHALL give access to getCategories, lenBytes, lenChars, startsWith(prefix), endsWith(suffix) and slice(offset, length) on Categorical and Enum columns. e.toPhysical SHALL give the category indices.
type Medal = enum Gold, Silver, Bronze
let df = newDataFrame:
medal: [Silver, Gold, Silver]
echo df.select(col.medal.cat.getCategories)
echo df.select(col.medal.toPhysical).toList("medal", int)
TBD
- WHEN
cat.getCategoriesruns on an Enum column holding only Silver and Gold - THEN the result is Gold, Silver and Bronze
data-types modified
DataType values
Nim types map to DataType
Unchanged in this spec: DataType constants and predicates, Schemas, Casting, Full-range UInt64
native-bridge modified
Nim declarations mirror the C ABI
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release
Design
Design
Nim enums through strings
A Nim enum value crosses the ABI as its string ($v): a column is built as strings and cast to the Enum dtype (nq_series_cast), and read back as strings that are mapped to values with a table built from for v in T. Strings, not ordinals, are the stable identity: holey enums and enums with string values work, and a column read from a file maps to the Nim type as long as the names match.
bool is a Nim enum
bool is an enum in Nim, so the generic overloads use a private type class NimEnum = not bool and enum to keep bool on its own paths.
Categories in dtype specs
NqDtypeSpec already carries a categories array for this change; Rust builds FrozenCategories from it for Enum. Reading a column's categories uses two small calls (count, then one string each) to avoid inventing a string-list ABI.
Tasks
1. Bridge
- 1.1Add the Categorical and Enum dtype codes and Enum categories in
NqDtypeSpec - 1.2Add
nq_df_column_n_categories,nq_df_column_category,nq_series_castandnq_expr_cat; mirror them inffi.nim
2. Nim API
- 2.1Add the kinds,
categories,CategoricalandEnum(...); Nim enums indataType - 2.2Accept Nim enums in
series, blocknewDataFrame,toList,[], comparisons andisIn - 2.3Add
CatNameSpace,toPhysical; no min/max indescribe - 2.4Write
tests/test_categorical.nim; add it tonanuq.nimbleand.gitignore
3. Docs and integration
- 3.1README lists categoricals;
nimble testandnimble specexamplespass - 3.2Archive the change: update BACKLOG "More dtypes", add CHANGELOG lines
Revisions
057c2f9 Add categoricals: Categorical, Enum, Nim enums and the cat namespaceFirst version: design.md, proposal.md, specs/categoricals/spec.md, specs/data-types/spec.md, specs/native-bridge/spec.md, tasks.md
add-cloud-storage Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 4/4
- Archive
Proposal
Why
Polars reads and writes object stores (S3, Google Cloud Storage, Azure, plain HTTPS) by URI, and the book and explainers use public datasets that live there. The cost thread ("Weigh adding cloud storage to 0.6", https://claude.ai/artifact/F1haAENdb2wY6NGzJpQfab) measured the Polars features cloud, aws, gcp, azure and http at about +2% of the library (object_store, tokio, reqwest and rustls are already compiled in for streaming), and found HTTPS reads already working. Pietro asked for it in 0.6, with the databases and Excel (2026-11-01).
It is the fourteenth change of the 0.6 release.
What Changes
- Polars features
cloud,aws,gcp,azure,http. storageOptions: openArray[(string, string)](Python'sstorage_options) onscanCsv,readCsv,scanParquet,readParquet,scanIpc,readIpc,scanNdjson,readNdjson, on the four sinks (also partitioned), and onwriteCsv,writeParquet,writeIpc,writeNdjson. Empty options leave credentials to the environment (AWS_*,GOOGLE_*,AZURE_*variables, config files), as in Polars.- Writes to a cloud URI run through a sink (the eager writers write local files).
isCloudPath(path).
Capabilities
New Capabilities
cloud-storage: cloud URIs, storage options, writing to object stores.
Differences from Polars
| Nanuq | Python | Rust (py-2.1.0) | |---|---|---| | storageOptions = {"aws_region": "eu-west-1"} | storage_options={"aws_region": ...} | CloudOptions::from_untyped_config | | writeParquet("s3://...") | write_parquet("s3://...") | sink with cloud_options | | isCloudPath | (internal _is_supported_cloud) | CloudScheme::from_path |
- No
credential_provider(Python's callable that refreshes credentials) and noretriesargument; retries can go instorageOptions(max_retries). readExcel,readJsonandreadDatabasestay local.
Impact
src/rust/Cargo.tomlfeatures;src/rust/src/lib.rs:nq_cloud_options_new,nq_cloud_options_free, acloud_optionsargument on the four scans and inNqSinkOptions.src/nanuq.nim,src/nanuq/ffi.nim; newtests/test_cloud.nim(a local HTTP server, and a local S3 with moto whenmoto_serveris installed; CI installs it).docs/coverage/polars.json: the cloud row becomes covered.
Spec changes
cloud-storage modified
Cloud URIs
Every scan* and read* function for CSV, Parquet, IPC and NDJSON files SHALL accept a cloud URI (s3://, gs://, az://, abfss://, hf://, http://, https://) in place of a local path, globs included. isCloudPath(path) SHALL tell such URIs from local paths.
echo isCloudPath("s3://polar-bears/census.parquet")
echo isCloudPath("https://example.org/bears.csv")
echo isCloudPath("data/bears.csv")
TBD
- WHEN
readParquet("http://127.0.0.1:<port>/bears.parquet")runs against a local - HTTP server
- THEN the frame equals the file's
Storage options
The cloud-capable reads, scans, writes and sinks SHALL take storageOptions, key/value pairs as Python's storage_options (aws_region, aws_endpoint_url, google_service_account, azure_storage_account_name, ...). Without them, credentials SHALL come from the environment as in Polars. Unknown keys SHALL be ignored, as in Polars; a failed request SHALL raise IOError.
let opts = {"aws_region": "eu-west-1", "aws_skip_signature": "true"}
let lf = scanParquet("s3://polar-bears/census.parquet", storageOptions = opts)
echo lf is LazyFrame
TBD
- WHEN
readParquet("s3://no-such-bucket/x.parquet", storageOptions = opts)runs - against a local S3
- THEN
IOErroris raised
Writing to object stores
writeParquet, writeCsv, writeIpc, writeNdjson and the sinks (also partitioned) SHALL write to a cloud URI, with storageOptions; the eager writes SHALL go through a streaming sink.
let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380]))
let opts = {"aws_endpoint_url": "http://127.0.0.1:9000", "aws_allow_http": "true"}
let sink = df.lazy.sinkParquet("s3://polar-bears/out.parquet", lazy = true,
storageOptions = opts)
echo sink is LazyFrame # collect(sink) writes the file
TBD
- WHEN a frame is written to
s3://nanuq/bears.parqueton a local S3 (moto) and read - back with the same
storageOptions - THEN the frames are equal
Tasks
1. Implementation
- 1.1Polars features cloud, aws, gcp, azure, http
- 1.2storageOptions on scans, reads, sinks and writes; cloud writes through sinks
- 1.3tests/test_cloud.nim (HTTP server, moto S3), CI installs moto
- 1.4CHANGELOG, coverage row
Revisions
889d13f Add cloud storage and 30 functions from the Polars coverage mapFirst version: proposal.md, specs/cloud-storage/spec.md, tasks.md
add-column-access-and-nulls Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 12/12
- Archive
Proposal
Why
Getting data out of Nanuq is slow and incomplete. toSeq makes one FFI call per cell, and nothing can represent a missing value: reading a null raises, and Nim data with gaps can't be built at all. Most of the backlog is blocked on this. That includes penguins (it has NAs), the ggplotnim module, Datamancer and Arraymancer interop, and nimib tables. Polars also works with nulls everywhere, so the API should expose them before outside users arrive.
This change takes up two BACKLOG.md entries: "Column access as Nim seqs without per-cell calls" (API) and the nulls half of "Nulls and more dtypes" (API). Dates and datetimes stay in the backlog.
What Changes
- Whole columns cross the boundary in one FFI call (two for strings), with a validity mask, for int64, float64, bool and string.
toSeq(df, col, T)uses the bulk path. It raisesNanuqErrorif the column has nulls; today it raises too, but only when it reaches the first null.- New
toSeq(df, col, Option[T])returnsseq[Option[T]], withnonefor nulls. - New null-aware single cells:
df[col, row, Option[T]]. - New
nullCount(df, col)andhasNulls(df, col). - New
series(name, openArray[Option[T]])builds columns with nulls from Nim. readCsvgainsnullValues(e.g.@["NA"]), so files like penguins load with real nulls instead of the string"NA".- New expressions
isNull,isNotNullandfillNull(value), anddropNullson LazyFrame and DataFrame (all columns, or a subset). - Reading a column as
floataccepts integer columns, and reading it asstringaccepts any dtype. Reading asintstays strict, so floats are not truncated.
Capabilities
New Capabilities
missing-values: how nulls are represented, built, read, tested, filled and dropped in the Nim API.
Modified Capabilities
dataframe-api: the "Building and reading data" requirement now covers bulk column reads, the dtype rules for reading, andreadCsvnull markers.native-bridge: a new requirement that columns cross the C ABI in bulk with a validity mask, not cell by cell.
Differences from Polars
Expected differences from Polars' Rust and Python APIs:
- Strict reads. Python's
Series.to_list()returnsNonefor nulls, andto_numpy()turns an integer column with nulls into floats with NaN. Nim's static types can't holdNonein aseq[int], sotoSeq(df, col, T)raises on nulls, andOption[T]is the explicit opt-in. This is closest to Rust'scont_slice(), which errors when there are nulls. - No NaN for nulls. Like Polars, Nanuq keeps NaN (a float value) and null (missing) distinct. It never converts one into the other the way
to_numpy()does. - Per-column counts.
nullCount(df, col)andhasNulls(df, col)take a column name. Python'sDataFrame.null_count()returns a one-row DataFrame with a count per column, and isn't added here. - Cell access. Polars has no cell-level null test; Python's
df[row, col]returnsNone. Nanuq's equivalent isdf[col, row, Option[T]]. - Names follow Polars in camelCase:
is_null→isNull,is_not_null→isNotNull,fill_null→fillNull,drop_nulls→dropNulls,null_count→nullCount,has_nulls→hasNulls,null_values→nullValues.
Impact
rust/src/lib.rs: new column export functions (nq_df_column_{i64,f64,bool}, a two-step string export),nq_series_new_*variants with validity,nq_df_null_count,nq_df_cell_is_null,nq_df_read_csvwith null values,nq_expr_fill_null,nq_lf_drop_nulls, andIsNull/IsNotNullappended toNqUnary. Adding the enum values at the end keeps the existing order. The Rust library is rebuilt, so the first CI run takes about 10 min.src/nanuq/ffi.nimandsrc/nanuq.nim: the matching declarations and API. Importsstd/options.tests/: new tests for nulls and bulk reads, plus a small CSV fixture with NA values.- The per-cell getters stay and keep their behavior. Nothing that works today breaks, except that
toSeqon a column with nulls now fails up front.
Spec changes
dataframe-api modified
Building and reading data
Unchanged in this spec: Automatic memory management, Reading columns by type, Expressions and lazy queries, HTML tables, Block syntax for building a DataFrame, Column shorthand, True division, Errors as PolarsError
missing-values modified
Purpose: How Nanuq represents missing values (Polars nulls) in its Nim API: building data with gaps, reading it back, and testing, filling and dropping nulls in queries.
Nulls are read as Option
Reading a column or a cell with the type Option[T] SHALL return none(T) for each null and some(value) otherwise, for T in int, float, bool and string.
- WHEN a column holds 1, null, 3 and is read with
toSeq(df, "a", Option[int]) - THEN the result is
@[some(1), none(int), some(3)]
- WHEN the null cell is read with
df["a", 1, Option[int]] - THEN the result is
none(int)
Plain reads refuse nulls
Reading a column or a cell with a plain type T SHALL raise NanuqError if the values read include a null, and the message SHALL name the column.
- WHEN a column with one null is read with
toSeq(df, "a", int) - THEN
NanuqErroris raised before any value is returned, naming column "a"
Inspecting nulls
The API SHALL report the number of nulls in a column and whether it has any.
- WHEN a column of 3 values has 1 null
- THEN
nullCount(df, "a")is 1 andhasNulls(df, "a")is true
- WHEN a column has no nulls
- THEN
nullCountis 0 andhasNullsis false
Building columns with nulls
series SHALL accept openArray[Option[T]] for int, float, bool and string, storing none as null with the same dtype as the plain version.
- WHEN a DataFrame is built from
series("a", [some(1), none(int)]) - THEN
dtype(df, "a")is "i64",nullCount(df, "a")is 1, and reading it asOption[int]gives back the input
CSV null markers
readCsv SHALL accept a list of strings to read as null. Without it, behavior is unchanged: only empty fields are null.
- WHEN a CSV file with "NA" in a numeric column is read with
nullValues = @["NA"] - THEN that column is numeric and the "NA" fields are null
Null expressions
The API SHALL provide isNull and isNotNull on expressions (giving booleans), and fillNull replacing nulls with a literal or an expression.
- WHEN a LazyFrame is filtered with
col("a").isNotNulland collected - THEN the result has no nulls in column "a"
- WHEN
withColumns(col("a").fillNull(0))is applied to a column 1, null, 3 - THEN column "a" becomes 1, 0, 3
Dropping rows with nulls
LazyFrame and DataFrame SHALL provide dropNulls, removing rows with a null in any column, or only in the named columns when a subset is given.
- WHEN
dropNulls(["a"])is applied to rows where "a" has one null and "b" another, in different rows - THEN only the row with the null in "a" is removed
Unchanged in this spec: Interpolation, Null literal, Filling nulls in whole frames
native-bridge modified
Columns cross in bulk
Reading a whole column into Nim SHALL take a constant number of FFI calls, independent of the number of rows, and SHALL transfer a validity mask alongside the values so nulls are not lost or replaced by placeholder values.
- WHEN a 1,000,000-row float column is read into a Nim seq
- THEN at most two FFI calls are made for that column
- WHEN a column with nulls crosses the boundary
- THEN Nim receives, for every row, whether the value is valid
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Nim declarations mirror the C ABI, Linking the static library, Library version check, Formatted cells, Polars version matches a py-polars release
Design
Design
Context
Today toSeq loops over rows and calls nq_df_get_{i64,f64,str} once per cell. Each call looks up the column, builds an AnyValue and checks the type. A null makes extract fail, so the call returns an error. Series can only be built from plain arrays. nq_df_read_csv uses CsvReadOptions::default() with a header and no null markers. NqUnary is a #[repr(C)] enum mirrored in ffi.nim.
Goals / Non-Goals
Goals:
- One FFI call per numeric or bool column and two per string column, whatever the height.
- No null is ever silently turned into a value (0, NaN, "").
- Keep the ABI style: borrow arguments, caller frees, errors through
nq_last_error.
Non-Goals:
- Zero-copy. Values are still copied into Nim memory. Arrow C Data Interface sharing stays in the backlog.
- Dates, datetimes and other dtypes (still in the backlog).
- A null-aware
Seriesread API. Reads go through DataFrame columns only, as today.
Decisions
Caller-allocated buffers for fixed-width columns
nq_df_column_i64(df, name, values: *mut i64, valid: *mut bool, len) -> bool (and _f64, _bool). Nim allocates height slots in seq[T] and seq[bool] and passes pointers. Rust casts the column to the target dtype (see the dtype rules below), checks len == height, and fills both buffers in one pass over chunked_array.iter() (one Option<T> per row).
- Why: Nim owns the memory, so there is no extra free function and no double-ownership risk. Filling is a single tight loop.
- Alternative: Rust allocates and returns a pointer plus a free function. That needs one more call and one more type to free, with no gain.
- Alternative: return values only, and signal nulls through a separate
null_count/is_nullcall. That is not constant-call when there are nulls.
Strings in two calls
nq_df_column_str_size(df, name) -> i64 returns the total UTF-8 byte length (-1 on error). nq_df_column_str(df, name, data: *mut u8, data_len, offsets: *mut u64, valid: *mut bool, len) -> bool writes the concatenated bytes and len + 1 offsets, which is Arrow's string layout. Nim then slices data into strings. Nulls have equal consecutive offsets and valid = false.
- Why: there is no per-string allocation across the boundary, and the layout matches Arrow, so moving to zero-copy later stays close.
- Alternative: return an array of C strings to free one by one. That costs N allocations and frees.
Dtype rules on the Rust side
For float, Rust casts any numeric dtype to Float64. For string, it casts any dtype to String. For int, it accepts only integer dtypes and casts them to Int64. For bool, it requires Boolean. Anything else is an error naming the column and its dtype. Casting in Rust reuses Polars' formatting and is a single vectorised operation.
Strict vs Option in Nim
toSeq(df, col, T) calls the bulk function and raises NanuqError if any valid[i] is false: "column 'a' has N nulls; read it as Option[T] or fill them first". toSeq(df, col, Option[T]) builds some/none from the mask. Both share one internal readColumn per type returning (values, valid). The single-cell df[col, row, Option[T]] uses a new nq_df_cell_is_null(df, name, row, out: *mut bool) together with the existing getters, because a single cell doesn't need the bulk path. That function is internal: the Nim API has no cell-level isNull (see proposal, "Differences from Polars"). nullCount uses nq_df_null_count, and hasNulls is nullCount > 0.
- Why strict by default: a null that silently becomes 0 is the bug this change is meant to prevent. Users who want defaults write
fillNullin the query, or map over the Option seq.
Building with nulls
nq_series_new_{i64,f64,bool,str}_opt(name, data, valid, len). Rust builds Vec<Option<T>> and Series::new. On the Nim side, series(name, openArray[Option[T]]) fills a values buffer (default value where none) and a mask.
Expressions and dropNulls
- Append
IsNullandIsNotNullto the end ofNqUnary, so existing values keep their numbers, and mirror them inffi.nim. nq_expr_fill_null(e, value: *const Expr) -> *mut Expr. In Nim,fillNulltakes anExpror a literal throughlit, like the binary operators.nq_lf_drop_nulls(lf, names: *const *const c_char, len) -> *mut LazyFrame, wherelen == 0means all columns. It maps toLazyFrame::drop_nulls(None | Some(selector)). The DataFrame shortcut goes throughlazy/collect, like the other eager methods.
CSV null markers
nq_df_read_csv gains null_values: *const *const c_char, len. With len == 0 it behaves as today. Otherwise it sets CsvParseOptions::with_null_values( Some(NullValues::AllColumns(..))). In Nim, readCsv(path, nullValues: openArray[string] = []) keeps today's calls source-compatible. The old one-argument C function is replaced, which is fine because the Nim wrapper is the only caller.
Risks / Trade-offs
- [Polars 0.55 API names, such as the
drop_nullsselector type and the null-values option path, may differ from the above] → Check against the 0.55 docs while implementing; the behavior in the specs doesn't depend on them. - [Changing
toSeqto fail up front on nulls] → It already failed at the first null; only the timing and message change. Note it in the CHANGELOG. - [Rust rebuild in CI costs about 10 min once] → Expected for any ABI change; the cache covers later runs.
- [The
ffi.nimandlib.rssignatures drift apart] → Every new function gets a test that calls it through the Nim API.
Tasks
1. Bulk column reads
- 1.1Add
nq_df_column_{i64,f64,bool}with caller-allocated values and validity buffers and the dtype rules from design.md, and mirror them inffi.nim; verifycargo build --releasepasses - 1.2Add
nq_df_column_str_sizeandnq_df_column_str(bytes, offsets, validity), and mirror them inffi.nim; verifycargo build --releasepasses - 1.3Reimplement
toSeq(df, col, T)for int, float, bool and string on the bulk path, raisingNanuqErrornaming the column when there are nulls; verify the existing tests still pass and new tests cover int→float, float→int error, bool and any→string
2. Reading and inspecting nulls
- 2.1Add
toSeq(df, col, Option[T])from the validity mask; verify with a test on a column 1, null, 3 - 2.2Add
nq_df_null_countandnq_df_cell_is_null, plusnullCount,hasNullsanddf[col, row, Option[T]]in Nim; verify with tests - 2.3Add
nq_series_new_*_optandseries(name, openArray[Option[T]])for the four types; verify a round-trip test (build with nulls, read back as Option,dtypeunchanged)
3. Nulls in queries and IO
- 3.1Append
IsNullandIsNotNulltoNqUnaryin Rust andffi.nim, and addisNull/isNotNullon Expr; verify with a filter test - 3.2Add
nq_expr_fill_nullandfillNull(Expr or literal); verify with a test - 3.3Add
nq_lf_drop_nullsanddropNullson LazyFrame and DataFrame (all columns or a subset); verify with tests for both forms - 3.4Add null markers to
nq_df_read_csvandreadCsv(path, nullValues = []); addtests/data/with_na.csvwith "NA" fields; verify that a numeric column with NA reads as f64/i64 with nulls, and that calling withoutnullValuesbehaves as before
4. Docs and integration
- 4.1Update README "What is there" and the
toSeqdoc comments for Option reads,nullCount,hasNulls,fillNull,dropNullsandnullValues; verifynimble testandnimble examplepass - 4.2Check that CI is green on the PR, including the one-off Rust rebuild
Workflow follow-up
Revisions
bb8c4a6 Archive add-column-access-and-nullsFirst version: .openspec.yaml, design.md, proposal.md, specs/dataframe-api/spec.md, specs/missing-values/spec.md, specs/native-bridge/spec.md, tasks.md
add-column-selectors Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 10/10
- Archive
Proposal
Why
Real tables have many columns, and many queries treat a group of them the same way: the mean of every numeric column, every column except the ID, all the weight_* columns. Nanuq can only name columns one at a time today. Polars solves this with selectors, and the 0.2 explainer post needs them (the census scene "mean of every numeric column per station, except the cub count").
This is the fifth change of the 0.2 release (see the Polars coverage map, area "Column selection"). It has no BACKLOG.md entry. Pietro made the API choice on 2026-10-31 in the doc "Nanuq 0.2: API choices the explainer forces": select by Nim type through col, with all(), exclude, and regex. No set operators in 0.2. Add name.suffix/name.prefix, because applying two aggregations to one selector otherwise gives duplicate names.
What Changes
- By Nim type:
col(SomeNumber)selects every numeric column. Each Nim typeclass maps onto a Polars dtype category: SomeIntegeris IntegerSomeSignedIntandSomeUnsignedIntare the signed and unsigned integersSomeFloatis Float
A concrete type selects exactly that dtype (col(int) is i64, col(string) is str), and several types select their union: col(float, int). A type with no dtype, such as col(seq[int]), does not compile.
- By name:
col("a", "b")selects several columns,all()selects every column, andcol("^weight_.*$")selects by regex, as in Polars. exclude:col(SomeNumber).exclude("cubs")andall().exclude("id", "name").- Selectors are expressions: a
Selectorconverts toExpr, socol(SomeNumber).mean,select(all().exclude("id"))andagg(col(SomeFloat).max)all work, and Polars expands the expression to one column per selected column. - Output names:
e.name.suffix("_mean")ande.name.prefix("avg_"). They rename every column an expression produces, for exampleagg(col(SomeNumber).mean.name.suffix("_mean"), col(SomeNumber).max.name.suffix("_max")). - The ABI stays
0.2.0-dev, and no Polars features are added.
Capabilities
New Capabilities
column-selectors: selecting columns by Nim type, by several names, by regex or all of them, withexclude, and renaming the outputs withname.suffix/name.prefix.
Modified Capabilities
native-bridge: the dtype category enum joins the ones that keep the same order in Rust andffi.nim.
Differences from Polars
Expected differences from Polars' Rust and Python APIs:
- Nim types instead of a selectors module. Python's
cs.numeric(),cs.integer(),cs.float(),cs.string()andcs.by_dtype(pl.Int64)becomecol(SomeNumber),col(SomeInteger),col(SomeFloat),col(string)andcol(int). This is the same idea ascast(int32). There is nocsnamespace. - No set operators. Python's
cs.numeric() - cs.by_name("year")and|,&,^,~are left out, because on expressions-already means subtraction.excludecovers the common case. excludetakes names only. Excluding by dtype (exclude(pl.Int64)) is left for later.colwith one name stays anExpr. Several names, types, orall()give aSelector. ASelectorconverts toExprautomatically, so it works wherever an expression does.- Not in this change:
cs.starts_with,ends_with,contains,by_index,first/last,temporal,categorical,name.map,name.keepandname.to_uppercase. Regex covers the name patterns. - Names follow Polars in camelCase:
name.suffixandname.prefixare spelled as in Polars.
Impact
src/rust/src/lib.rs:nq_expr_selectorbuilds a PolarsSelectorfrom names, dtype codes, a dtype category, a wildcard flag and excluded names, and returns it as anExpr.nq_expr_name_affixadds a suffix or prefix.- New
#[repr(C)]enumNqDtypeClass. src/nanuq/ffi.nimandsrc/nanuq.nim: theSelectorvalue type with its converter toExpr,coloverloads for types, typeclasses and several names,all,exclude,name.suffixandname.prefix.tests/test_selectors.nim: each selector form,exclude, regex, use inselect,withColumnsandagg, and suffixes that avoid duplicate names.README.mdlists the selectors.
Spec changes
column-selectors modified
Selecting by Nim type
col SHALL accept Nim types and typeclasses and return a Selector.
SomeNumber,SomeInteger,SomeSignedInt,SomeUnsignedIntandSomeFloatSHALL select the matching Polars dtype category.- A concrete type SHALL select the dtype
dataTypegives it. - Several types SHALL select their union.
- A type without a dtype SHALL not compile.
- WHEN
select(col(SomeNumber))runs on columnsstation(str),bears(i64) andweight(f64) - THEN the result has columns
bearsandweight
- WHEN
select(col(float, string))runs on the same frame - THEN the result has columns
stationandweight
- WHEN
col(seq[int])is compiled - THEN compilation fails
Selecting by name
col(a, b, ...) with two or more names SHALL return a Selector for those columns in that order, and all() SHALL select every column. col with one name SHALL keep returning an Expr, and a name that starts with ^ and ends with $ SHALL be a regex.
- WHEN
select(col("^weight_.*$"))runs on columnsweight_kg,weight_lbandname - THEN the result has columns
weight_kgandweight_lb
Excluding columns
Selector SHALL support exclude(names: varargs[string]), which removes the named columns from the selection.
- WHEN
select(all().exclude("id"))runs on columnsid,aandb - THEN the result has columns
aandb
Selectors as expressions
A Selector SHALL convert to Expr automatically. An expression built from it SHALL apply to every selected column and keep each column's name.
- WHEN a frame is grouped by
stationand aggregated withcol(SomeNumber).exclude("cubs").mean - THEN the result has
stationand one mean column per remaining numeric column, with the original names
Output name suffix and prefix
Expr SHALL support name.suffix(s) and name.prefix(s), which append or prepend s to the name of every column the expression produces.
- WHEN
agg(col(SomeFloat).mean.name.suffix("_mean"), col(SomeFloat).max.name.suffix("_max"))runs on float columnsaandb - THEN the result has columns
a_mean,b_mean,a_maxandb_max
Unchanged in this spec: Operators on selectors
native-bridge modified
Nim declarations mirror the C ABI
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release
Design
Design
Context
In Polars 0.55, a Selector (polars_plan::dsl::Selector) is a tree: ByName, Matches(regex), ByDType(DataTypeSelector), Wildcard, plus set operations. DataTypeSelector has AnyOf([DataType]), Integer, SignedInteger, UnsignedInteger, Float and Numeric, among others. Selector::exclude_cols(names) removes names, and Selector::as_expr() turns a selector into an Expr that Polars expands against the schema. col("^...$") is already a regex selector. Expr::name().suffix(s) and .prefix(s) rename outputs.
Goals / Non-Goals
Goals:
- Selectors in idiomatic Nim (types and typeclasses), with no extra namespace to import.
- No opaque selector handles across the ABI.
Non-Goals:
- Set operators, by-index selection, and name helpers beyond regex.
Decisions
Selector is a Nim value built into an Expr on use
A Nim Selector object holds what was asked for: names: seq[string], dtypes: seq[DataType], classes: set[DtypeClass], wildcard: bool and excluded: seq[string]. exclude returns a copy with more excluded names. A converter toExpr(s: Selector): Expr makes one call:
nq_expr_selector(names: *const *const c_char, n_names: usize, dtypes: *const NqDtype,
n_dtypes: usize, classes: u32 /* bit set of NqDtypeClass */,
wildcard: bool, excluded: *const *const c_char, n_excluded: usize)
-> *mut Expr
Rust takes the union of the parts (ByName | ByDType(AnyOf) | ByDType(category) | Wildcard), applies exclude_cols, and returns as_expr().
- Why: it is the same pattern as the conditional chain (built in Nim, crossed once). Selectors stay plain values, and
$shows Polars' rendering of the selector. - Alternative: an opaque
NqSelectorwith its own free function. That means more ABI surface, and it gains nothing until set operators exist.
Types and typeclasses
col(T: typedesc) is a macro. It looks at the type it is given:
SomeNumber,SomeInteger,SomeSignedInt,SomeUnsignedIntandSomeFloatmap to the matchingDtypeClass.- A concrete type maps through
dataType(T), socol(int)isInt64andcol(int8)isInt8, the same rules ascast. col(float, int)takes several types and unions them.- Any other type is a compile error with the message of
dataType.
Several names
col(a, b: string, more: varargs[string]) returns a Selector, so col("a") keeps returning Expr with no ambiguity. all() sets wildcard. Regex needs no new code, because col("^w.*$") already passes the pattern to Polars.
Output names
proc name(e: Expr): ExprName returns a small wrapper. suffix(n: ExprName, s) and prefix(n: ExprName, s) call nq_expr_name_affix(e, s, is_prefix). A Selector reaches name through the converter.
Risks / Trade-offs
- Converters make overload errors harder to read. They are limited to
Selector -> Expr, the same asThen -> Expr. - Typeclass dispatch in a macro depends on how Nim represents
SomeNumbersymbols. The tests cover each typeclass and a concrete type.
Tasks
1. Bridge
- 1.1Add
#[repr(C)]NqDtypeClass(Numeric, Integer, SignedInteger, UnsignedInteger, Float) andnq_expr_selector(names, dtype codes, class bit set, wildcard, excluded names) - 1.2Add
nq_expr_name_affix(suffix or prefix) - 1.3Mirror both in
ffi.nim; verify thatcargo build --releasepasses
2. Nim API
- 2.1Add the
Selectorvalue type, its converter toExpr, and$ - 2.2Add
colfor Nim types and typeclasses (macro), several types, and several names; addall() - 2.3Add
exclude(names)onSelector - 2.4Add
name.suffixandname.prefix - 2.5Write
tests/test_selectors.nim: each typeclass and concrete type,col(float, int),col("a", "b"),all(), regex,exclude, use inselect/withColumns/agg, two aggregations with suffixes, andcol(seq[int])not compiling; add it tonanuq.nimbleand.gitignore
3. Docs and integration
- 3.1List the selectors in the README "What is there"; verify that
nimble testandnimble examplepass - 3.2Check that CI is green on the PR
Workflow follow-up
Revisions
2b080c0 Add column selectors (implements add-column-selectors)First version: .openspec.yaml, design.md, proposal.md, specs/column-selectors/spec.md, specs/native-bridge/spec.md, tasks.md
add-coverage-easy-wins-0-6 Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 5/5
- Archive
Proposal
Why
The Polars coverage map (nanuq#60, docs/coverage/polars.json) lists the Python API Nanuq still misses. Its thread picked out 30 items that each take hours, not days (/mnt/project-files/nanuq-0.6/easy-wins.md), and Pietro asked for all three groups in 0.6 (2026-11-01): pure Nim helpers, small bridge calls on features already compiled in, and items that turn on one more Polars feature.
It is the thirteenth change of the 0.6 release.
What Changes
- Pure Nim: empty frames (
newDataFrame(schema = ...),clear(n)),isEmpty,getColumnIndex,rowsByKey, frameshiftanddropNans, LazyFrameshift,first,last,dt.epoch(unit), table formatting options (setTblFormatting,setAsciiTables,setTblHide*,setTblCellAlignment, ...),binon Series. - Small bridge calls:
eqMissing,neMissing,nth,cumulativeEval,roundSigFigs,dt.century,dt.millennium,dt.dstOffset,dt.baseUtcOffset,timeRange,timeRanges,str.escapeRegex,concatArr, CSVcommentPrefix,scanParquet(hivePartitioning),cache,QueryOptFlags(collect(optimizations),withOptimizations),rechunk,shrinkToFit,nChunks,matchToSchema,readOds. - One more Polars feature each:
isClose(is_close),mergeSorted(merge_sorted),dt.addBusinessDays,dt.isBusinessDay,businessDayCount(business),str.normalize(string_normalize),reinterpret(reinterpret),readIpcStreamandwriteIpcStream(ipc_streaming), andcseso that the common subplan and subexpression optimizations exist (py-polars has them on).
Capabilities
Modified Capabilities
frame-utilities: empty frames, frame shortcuts, schema matching, merging sorted frames, query optimizations.temporal: more date parts, time ranges, business days.expressions: null-aware comparisons, closeness,nth,cumulativeEval,roundSigFigs,reinterpret,concatArr.strings:escapeRegex,normalize.series: thebinnamespace on Series.csv-io: comment lines.parquet-ipc: Hive partitioning switch, IPC streams.excel-io:readOds.inspection: table formatting options.
Differences from Polars
| Nanuq | Python | Rust (py-2.1.0) | |---|---|---| | newDataFrame(schema = {...}) | pl.DataFrame(schema=...) | DataFrame::empty_with_schema | | clear(n) | clear(n) | (Python only) | | isEmpty | is_empty | is_empty | | getColumnIndex | get_column_index | get_column_index | | rowsByKey(key, K, T, unique) | rows_by_key(key, named, include_key, unique) | (Python only) | | shift, dropNans, first, last on frames | same | shift, drop_nans, first, last | | dt.epoch(EpochUnit) | dt.epoch(time_unit) | (Python only) | | setTblFormatting, setAsciiTables, setTblHide*, ... | Config.set_tbl_formatting, ... | POLARS_FMT_* variables | | s.bin.* | Series.bin.* | | | eqMissing, neMissing | eq_missing, ne_missing | eq_missing, neq_missing | | nth(indices) | pl.nth(*indices) | dsl::nth | | cumulativeEval(expr, minSamples) | cumulative_eval | cumulative_eval | | roundSigFigs(digits) | round_sig_figs | round_sig_figs | | dt.century, dt.millennium, dt.dstOffset, dt.baseUtcOffset | same | same | | timeRange, timeRanges | pl.time_range(s) | time_range(s) | | str.escapeRegex, str.normalize(UnicodeForm) | escape_regex, normalize | same | | concatArr | pl.concat_arr | concat_arr | | commentPrefix | comment_prefix | with_comment_prefix | | hivePartitioning | hive_partitioning | HiveOptions | | cache, QueryOptFlags, withOptimizations | cache, QueryOptFlags, collect(optimizations=) | cache, OptFlags | | rechunk, shrinkToFit, nChunks | rechunk, shrink_to_fit, n_chunks | rechunk_mut, shrink_to_fit, max_n_chunks | | matchToSchema | match_to_schema | match_to_schema | | readOds | read_ods | (calamine) | | isClose | is_close | is_close | | mergeSorted(other, key) | merge_sorted | merge_sorted | | dt.addBusinessDays, dt.isBusinessDay, businessDayCount | same | same | | reinterpret(signed) | reinterpret(signed=) | reinterpret | | readIpcStream, writeIpcStream | read_ipc_stream, write_ipc(..)/write_ipc_stream | IpcStreamReader, IpcStreamWriter |
rowsByKeyreturns anOrderedTableof Nim objects or tuples (T); the key column is in the rows only ifThas a field for it (Python:include_key,named).timeRange/timeRangesneedstartandstop(Python defaults to the whole day).matchToSchemasets the same policy for every column and has no struct-field policies or fill expressions (Python takes a dict per column).QueryOptFlags.nonekeeps type coercion and checks on, as Python's; Python's deprecatedcollect(predicate_pushdown=...)keywords are not offered.- Business days take
weekMask: array[7, bool]andholidays: openArray[Date], androllis aRollenum (Python strings). nthreturns an expression, not a selector (it cannot be combined with|).- Table options are switches (
setTblHideColumnNames(false)turns it off again); thewithConfigblock takes the most used of them.
Impact
src/rust/src/lib.rs:nq_expr_win,nq_expr_business_day_count,nq_expr_time_range,nq_expr_concat_arr,nq_expr_nth,nq_lf_with_optimizations,nq_lf_cache,nq_lf_drop_nans,nq_lf_merge_sorted,nq_lf_match_to_schema,nq_df_rechunk,nq_df_shrink_to_fit,nq_df_n_chunks, IPC stream read/write, CSVcomment_prefix, Parquethive; featuresis_close,merge_sorted,business,string_normalize,reinterpret,ipc_streaming,cse.src/nanuq.nim,src/nanuq/ffi.nim; newtests/test_easywins6.nimandtests/data/bears.ods.docs/coverage/polars.json: these rows become covered.
Spec changes
csv-io modified
Comment lines
readCsv and scanCsv SHALL skip lines starting with commentPrefix (none when empty).
import std/streams
echo readCsv(newStringStream("# measured 2026\nbear,kg\nAda,410\n"), commentPrefix = "#")
TBD
- WHEN a CSV starting with "# note" is read without
commentPrefix - THEN "# note" is the first column name
Unchanged in this spec: Scanning CSV, CSV read options, CSV write options, Reading CSV from a stream, Quoting, encoding and new column names
excel-io modified
Reading OpenDocument
readOds SHALL read a sheet of an .ods file with the options of readExcel.
echo readOds("tests/data/bears.ods")
TBD
- WHEN an .ods sheet with numeric cells is read
- THEN those columns are Float64
Unchanged in this spec: Writing Excel, Reading Excel
expressions modified
Null-aware comparisons and closeness
eqMissing(other) and neMissing(other) SHALL compare as == and != with null equal to null, never giving null. isClose(other, absTol = 0.0, relTol = 1e-9, nansEqual = false) SHALL be true where abs(a - b) <= max(relTol * max(abs(a), abs(b)), absTol).
let df = newDataFrame(series("a", [some(1.0), none(float)]), series("b", [some(1.05), none(float)]))
echo df.select(col("a").eqMissing(col("b")).alias("eq"),
col("a").isClose(col("b"), absTol = 0.1).alias("close"))
TBD
- WHEN
eqMissingcompares null with null - THEN the result is true
More expression functions
nth(indices) SHALL select columns by position (negative from the end). cumulativeEval(expr, minSamples = 1) SHALL run expr on the growing window up to each row, roundSigFigs(digits) SHALL round to significant figures, reinterpret(signed) SHALL read 64-bit integer bits as Int64 or UInt64, and concatArr(exprs) SHALL build fixed-size arrays per row.
let df = newDataFrame(series("x", @[1.0, 22.0, 333.0]), series("y", @[4.0, 5.0, 6.0]))
echo df.select(nth(-1), col("x").cumulativeEval(element().sum).alias("cum"),
col("x").roundSigFigs(1).alias("sig"), concatArr(col("x"), col("y")).alias("xy"))
TBD
- WHEN
cumulativeEval(element().sum)runs on 1, 2, 3 - THEN the result is 1, 3, 6
Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Ranking, Filtering inside expressions, Shape and position aggregations, Boolean aggregations, Entropy, Row count expression, Several window keys and selector concatenation
frame-utilities modified
Empty frames
newDataFrame(schema = {...}) SHALL build a frame with those columns and types and no rows (a Schema works too). clear(n = 0) on a DataFrame or LazyFrame SHALL keep the columns and types with no rows, or n rows of nulls. isEmpty on a DataFrame or Series SHALL be true when it has no rows.
let empty = newDataFrame(schema = {"bear": String, "kg": Int64})
echo empty
echo empty.isEmpty
echo newDataFrame(series("kg", @[410, 380])).clear(1)
TBD
- WHEN
df.clearruns - THEN its schema equals
df.schemaand its height is 0
Frame shortcuts
getColumnIndex(name) SHALL give a column's position (raising ColumnNotFoundError). rowsByKey(key, K, T, unique = false) SHALL group the rows, as T objects or tuples, by the values of key in order of appearance (with unique, the last row per key). shift(n, fillValue) and dropNans(subset) SHALL work on frames as on each column; LazyFrame first and last SHALL keep the first or last row. rechunk SHALL put each column in one chunk, shrinkToFit SHALL drop spare capacity, and nChunks SHALL count chunks.
import std/tables
let df = newDataFrame(series("station", @["A", "B", "A"]), series("rain", @[1.5, NaN, 3.0]))
echo df.getColumnIndex("rain")
echo df.rowsByKey("station", string, tuple[rain: float])
echo df.dropNans.shift(1)
TBD
- WHEN
getColumnIndex("nope")runs - THEN
ColumnNotFoundErroris raised
Schema matching
matchToSchema(schema, missingColumns, extraColumns, integerCast, floatCast) SHALL put the columns in the schema's order and types. A missing column SHALL raise unless missingColumns = Insert (nulls), an extra column SHALL raise unless extraColumns = Ignore, and integers and floats SHALL change type only with CastPolicy.Upcast.
let df = newDataFrame(series("b", @[1'i32]), series("a", @["x"]))
echo df.matchToSchema({"a": String, "b": Int64, "c": Float64},
missingColumns = MissingColumns.Insert, integerCast = CastPolicy.Upcast)
TBD
- WHEN the schema has a column the frame lacks and
missingColumnsisRaise - THEN
PolarsErroris raised
Merging sorted frames
mergeSorted(other, key) SHALL merge two frames sorted by key into one sorted frame.
let a = newDataFrame(series("k", @[1, 4]))
let b = newDataFrame(series("k", @[2, 3, 5]))
echo a.mergeSorted(b, "k").toList("k", int)
TBD
- WHEN both frames have the same columns, sorted by
key - THEN the result has all their rows, sorted
Query optimizations
cache SHALL mark part of a query to compute once. QueryOptFlags SHALL hold the optimization switches (all on by default; QueryOptFlags.none turns off all but type coercion and checks), applied with withOptimizations or collect(optimizations, engine).
let lf = newDataFrame(series("x", @[1, 2, 3])).lazy.filter(col("x") > 1)
echo lf.collect(QueryOptFlags.none).height
echo lf.cache.collect(QueryOptFlags(predicatePushdown: false)).height
TBD
- WHEN a query is collected with every optimization on and with
QueryOptFlags.none - THEN the rows are the same
Unchanged in this spec: Smaller expression functions, Names and meta, Comparing and stacking frames, Updating, upsampling and partitions, Operator methods and xor, Ranges per row, Inequality joins, Frame and Series helpers, Unstack, Rolling Nim functions, Data type of an expression
inspection modified
Table formatting options
setTblFormatting(TableFormat, roundedCorners), setAsciiTables, setTblHideColumnDataTypes, setTblHideColumnNames, setTblHideDataframeShape, setTblHideColumnSeparator, setTblDataframeShapeBelow, setTblColumnDataTypeInline, setTblCellAlignment, setTblCellNumericAlignment and setFmtTableCellListLen SHALL change how frames print; setConfig and withConfig SHALL take tblFormatting, asciiTables, tblHideColumnDataTypes, tblHideColumnNames, tblHideDataframeShape and tblCellAlignment, and resetConfig SHALL undo them all.
let df = newDataFrame(series("bear", @["Ada"]), series("kg", @[410]))
withConfig(tblFormatting = TableFormat.Markdown, tblHideDataframeShape = true):
echo df
TBD
- WHEN a frame prints inside
withConfig(asciiTables = true) - THEN its borders use
+,-and|
Unchanged in this spec: glimpse, describe, Display config, Scoped display config, Describe prints temporal values as Python
parquet-ipc modified
Hive partitioning switch
scanParquet and readParquet SHALL take hivePartitioning: true reads key=value directories as columns, false does not, none(bool) (default) decides by the path.
let base = getTempDir() / "nanuq-hive"
let df = newDataFrame(series("year", @[2024, 2025]), series("n", @[1, 2]))
df.lazy.sinkParquet(PartitionBy(basePath: base, key: @["year"], includeKey: false), mkdir = true)
echo scanParquet(base / "**/*.parquet", hivePartitioning = false).collect.columns
TBD
- WHEN the same files are scanned with
hivePartitioning = true - THEN the frame has a
yearcolumn
Arrow IPC streams
writeIpcStream(path, compression) SHALL write the Arrow IPC stream format, and readIpcStream SHALL read it from a path or a stream.
let path = getTempDir() / "bears.arrows"
newDataFrame(series("kg", @[410, 380])).writeIpcStream(path)
echo readIpcStream(path).toList("kg", int)
TBD
- WHEN a frame is written with
IpcCompression.Zstdand read back - THEN the frames are equal
Unchanged in this spec: Reading Parquet, Writing Parquet, Arrow IPC, Reading from streams
series modified
Binary functions on a Series
s.bin SHALL give the bin namespace on a Series, as on an expression.
let s = newDataFrame(series("b", @["ab", "c"])).select(col("b").cast(Binary)).getColumn("b")
echo s.bin.size
TBD
- WHEN
s.bin.sizeruns - THEN it equals
s.eval(col(s.name).bin.size)
Unchanged in this spec: Getting a Series, Reading a Series, Series operations, Series in frames, Series namespaces, Series as HTML, Columns from sized numbers
strings modified
Escaping and normalizing
str.escapeRegex SHALL escape regex metacharacters, and str.normalize(form = UnicodeForm.NFC) SHALL give the Unicode normal form (NFC, NFKC, NFD, NFKD).
let df = newDataFrame(series("s", @["a.b*c", "é"]))
echo df.select(col("s").str.escapeRegex.alias("escaped"),
col("s").str.normalize.str.lenChars.alias("chars"))
TBD
- WHEN "e" followed by a combining acute accent is normalized to NFC
- THEN the result is the one character "é"
Unchanged in this spec: The str namespace, Matching, Replacing and stripping, Slicing and padding, Joining strings in an aggregation, Building strings from columns, Title case, Splitting and extracting into lists and structs, Many patterns at once, JSON in strings
temporal modified
More date parts and time ranges
dt.epoch(EpochUnit) SHALL give the time since 1970-01-01 (whole seconds and days for Seconds and Days), dt.century and dt.millennium the century and millennium, dt.dstOffset and dt.baseUtcOffset the offsets of zoned datetimes as Durations. timeRange(start, stop, interval, closed) SHALL give times of day, timeRanges one list per row.
let df = newDataFrame(series("d", @[date(2000, 6, 1), date(2001, 1, 1)]))
echo df.select(col("d").dt.epoch(EpochUnit.Days).alias("days"),
col("d").dt.century.alias("century"))
echo select(timeRange(timeOfDay(9), timeOfDay(11), "1h").alias("t"))
TBD
- WHEN
dt.dstOffsetruns on 2026-07-01 12:00 in Europe/Rome - THEN the result is 1 hour
Business days
dt.addBusinessDays(n, weekMask, holidays, roll), dt.isBusinessDay(weekMask, holidays) and businessDayCount(start, stop, weekMask, holidays) SHALL count business days: Monday to Friday by default (weekMask, Monday first), minus holidays. roll SHALL say what a start date that is not a business day does (Raise, Forward, Backward).
let df = newDataFrame(series("d", @[date(2026, 10, 30)]))
echo df.select(col("d").dt.addBusinessDays(1).alias("next"),
col("d").dt.isBusinessDay.alias("business"))
echo select(businessDayCount(date(2026, 11, 2), date(2026, 11, 9)).alias("n")).toList("n", int)
TBD
- WHEN one business day is added to Friday 2026-10-30 with Monday 2026-11-02 a holiday
- THEN the result is 2026-11-03
Unchanged in this spec: Temporal values, Temporal ranges and durations, Parsing strings, Date and time parts, Formatting temporal values, Temporal arithmetic, Time zones, Dates from parts
Tasks
1. Implementation
- 1.1Pure Nim helpers (group A)
- 1.2Bridge calls on features already on (group B)
- 1.3Polars features is_close, merge_sorted, business, string_normalize, reinterpret, ipc_streaming, cse (group C)
- 1.4tests/test_easywins6.nim, spec examples
- 1.5CHANGELOG, coverage rows
Revisions
889d13f Add cloud storage and 30 functions from the Polars coverage mapFirst version: proposal.md, specs/csv-io/spec.md, specs/excel-io/spec.md, specs/expressions/spec.md, specs/frame-utilities/spec.md, specs/inspection/spec.md, specs/parquet-ipc/spec.md, specs/series/spec.md, specs/strings/spec.md, specs/temporal/spec.md, tasks.md
add-csv-options-and-scan Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 9/9
- Archive
Proposal
Why
Real CSV files are rarely clean. They use ; as a separator, mark missing values with words like "lots" or "?", have a preamble before the header, need a column read as another type, or come as a folder of daily files. Nanuq's readCsv handles only a header row and null markers, and writeCsv has no options at all. Python Polars handles all of these with keyword arguments, and its lazy scan_csv reads a glob of files without loading them first. The 0.2 explainer post needs this in two scenes: it reads a season of daily logs lazily, and it writes a report for a spreadsheet that expects ; and decimal commas.
This change takes up the "lazy scanCsv" part of the BACKLOG.md entry "More IO". Parquet and JSON stay in the entry. It is the sixth and last change of the 0.2 release (see the Polars coverage map, area "IO"). Pietro made the API choice on 2026-10-31 in the doc "Nanuq 0.2: API choices the explainer forces": named arguments with Polars' defaults, schemaOverrides taking DataType values, and a char separator.
What Changes
scanCsv(path, ...)returns aLazyFrame.pathcan be a glob such as"logs/*.csv", and every matched file must have the same columns.readCsv(path, ...)takes the same options and returns aDataFrame.readCsv(path)andreadCsv(path, nullValues = [...])keep working.- Read options, named as in Python Polars and with its defaults:
separator = ','hasHeader = truenullValues: openArray[string]schemaOverrides: openArray[(string, DataType)], e.g.{"bears": Int64}skipRows = 0nRows = none(int)columns: openArray[string](read only these)inferSchemaLength = some(100)(nonescans every row)ignoreErrors = falsedecimalComma = falsewriteCsv(df, path, ...)options:separator = ','includeHeader = truenullValue = ""quoteStyle = Necessary(a pure enumQuoteStyle:Necessary,Always,NonNumeric,Never)floatPrecision = none(int)decimalComma = falsenRows,inferSchemaLengthandfloatPrecisionalso accept a plainint, likesample'sseed.- The ABI stays
0.2.0-dev, and no Polars features are added (lazyandcsvalready include scanning and globs).
Capabilities
New Capabilities
csv-io: reading, scanning and writing CSV with options.
Modified Capabilities
native-bridge:NqQuoteStylejoins the enums that keep the same order in Rust andffi.nim.
Differences from Polars
Expected differences from Polars' Rust and Python APIs:
- Named arguments instead of Rust's builder. Rust's
CsvReadOptionsandLazyCsvReaderbuilders become named arguments, as in Python. separatoris achar(';'), where Python takes a one-character string. A multi-character separator does not compile.schemaOverridestakesDataTypevalues ({"bears": Int64}), likecast, not Nim types.quoteStyleis an enum (quoteStyle = Always), where Python takes a string.- Optional integers (
nRows,inferSchemaLength,floatPrecision) areOption[int], and also accept a plainint. readCsvisscanCsv(...).collect. The two take the same options and read the same data. Python'sread_csvhas a separate eager reader with a few extra options.- A glob of files with different columns fails. As in Polars,
scanCsvexpects the same columns in every file. Read the files separately and useconcat(how = Diagonal)instead. - Not in this change:
- Read options:
quote_char,comment_prefix,encoding,try_parse_dates(dates are not modelled yet),row_index_name,truncate_ragged_lines,missing_utf8_is_empty_string, and per-columnnull_values(a dict). schema(the full schema) andnew_columns.- CSV from a string (its own BACKLOG entry).
- Write options:
quote_char, the date and time formats,float_scientificandline_terminator. - Names follow Polars in camelCase:
has_header→hasHeader,null_values→nullValues,schema_overrides→schemaOverrides,n_rows→nRows, and so on.
Impact
src/rust/src/lib.rs:nq_lf_scan_csvmaps every read option ontoLazyCsvReader. It replacesnq_df_read_csv.nq_df_write_csvgains the write options.- New
#[repr(C)]enumNqQuoteStyle. src/nanuq/ffi.nim,src/nanuq.nim: the declarations,QuoteStyle,scanCsv, and the newreadCsvandwriteCsvsignatures.tests/test_csv.nim: each option, globs, and reading back whatwriteCsvwrote with the same options.README.mddocuments the options.BACKLOG.mdkeeps "More IO" for Parquet, JSON andscanParquet.
Spec changes
csv-io modified
Scanning CSV
The API SHALL provide scanCsv(path, ...), which returns a LazyFrame without reading the file until the query runs. path SHALL accept a glob that matches several files with the same columns. A glob whose files have different columns SHALL raise NanuqError when the query runs.
- WHEN
scanCsv(dir / "*.csv").collectruns on two files with the same columns and 2 and 3 rows - THEN the result has 5 rows
CSV read options
readCsv and scanCsv SHALL take these named options with Polars' defaults:
separator = ','andhasHeader = truenullValuesandschemaOverrides((string, DataType)pairs)skipRows = 0,nRows = none(int)andcolumns(all when empty)inferSchemaLength = some(100), wherenonescans all rowsignoreErrors = falseanddecimalComma = false
nRows and inferSchemaLength SHALL also accept a plain int.
- WHEN a file with
;separators and the value "lots" is read withseparator = ';', nullValues = ["lots"] - THEN the columns are split at
;and "lots" is null
- WHEN a column of whole numbers is read with
schemaOverrides = {"n": Float64} - THEN
dtype("n") == Float64
- WHEN a file with two preamble lines and 10 data rows is read with
skipRows = 2, nRows = 3 - THEN the header is the third line and the result has 3 rows
- WHEN a file with columns
a,bandcis read withcolumns = ["c", "a"] - THEN the result has columns
canda
CSV write options
writeCsv(df, path, ...) SHALL take these named options:
separator = ','andincludeHeader = truenullValue = ""quoteStyle = Necessary, a pure enumQuoteStyle(Necessary,Always,NonNumeric,Never)floatPrecision = none(int)(also a plainint)decimalComma = false
- WHEN a frame with 1.5 is written with
separator = ';', decimalComma = trueand read back with the same options - THEN the file holds
1,5and the value read back is 1.5
- WHEN a frame is written with
quoteStyle = Always - THEN every field in the file is quoted
- WHEN a frame with a null and 3.14159 is written with
nullValue = "NA", floatPrecision = 2 - THEN the file holds
NAand3.14
Unchanged in this spec: Reading CSV from a stream, Quoting, encoding and new column names, Comment lines
native-bridge modified
Nim declarations mirror the C ABI
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release
Design
Design
Context
readCsv calls nq_df_read_csv(path, null_values, n), which uses the eager CsvReadOptions reader. writeCsv calls nq_df_write_csv(df, path) with CsvWriter defaults. Polars 0.55 has LazyCsvReader::new(path) with with_separator, with_has_header, with_null_values, with_dtype_overwrite, with_skip_rows, with_n_rows, with_infer_schema_length, with_ignore_errors, with_decimal_comma and with_glob (on by default), ending in .finish(). CsvWriter has with_separator, include_header, with_null_value, with_quote_style(QuoteStyle), with_float_precision and with_decimal_comma.
Goals / Non-Goals
Goals:
- One reader in Rust for both eager and lazy reads, so their behavior can't drift.
- The option set the 0.2 explainer needs, with Polars' defaults.
Non-Goals:
- Every Python option. The rest come when someone needs them.
- An options object. Pietro chose named arguments, and an object overload can be added later.
Decisions
One scan function
nq_lf_scan_csv(path, separator: u8, has_header: bool,
null_values: *const *const c_char, n_nulls: usize,
override_names: *const *const c_char, override_dtypes: *const NqDtype,
n_overrides: usize, skip_rows: usize, n_rows: i64 /* <0: all */,
infer_schema_length: i64 /* <0: all rows */, ignore_errors: bool,
decimal_comma: bool) -> *mut LazyFrame
readCsv is scanCsv(...).collect in Nim, and columns becomes a select after the scan, which Polars pushes down into the reader. nq_df_read_csv is removed. That is fine within 0.2.0-dev.
- Why: one code path and one ABI function. The lazy plan gives projection pushdown for free.
- Alternative: keep an eager reader with its own options. That duplicates the options for a small speed gain on tiny files.
Separator as char
Nim's char is one byte, the same as Rust's u8. A non-ASCII char literal cannot be written, so no runtime check is needed.
Overrides as DataType
schemaOverrides: openArray[(string, DataType)] goes across as names plus NqDtype codes, the same encoding as cast. An Other dtype raises NanuqError.
Optional integers
Option[int] values cross as -1 for none. The parameters are typed int | Option[int] (nRows, inferSchemaLength and floatPrecision), so a plain int works without extra overloads; a private toOpt turns either into Option[int]. (The proposal planned plain-int overloads from a template; the generic parameter turned out simpler.)
writeCsv
nq_df_write_csv(df, path, separator, include_header, null_value, quote_style: NqQuoteStyle, float_precision: i32 /* <0: none */, decimal_comma) -> bool.
Risks / Trade-offs
readCsvthrough the lazy engine changes error messages for some malformed files. The tests keep the existing CSV tests passing.- Globs that match files with different columns fail. The proposal documents this, and the post uses diagonal concat.
Tasks
1. Bridge
- 1.1Add
nq_lf_scan_csvwith all read options (separator, header, nulls, overrides, skip rows, row limit, inference length, ignore errors, decimal comma); removenq_df_read_csv - 1.2Add
NqQuoteStyleand the write options tonq_df_write_csv - 1.3Mirror everything in
ffi.nim; verify thatcargo build --releasepasses
2. Nim API
- 2.1Add
scanCsvwith the read options, and makereadCsvscanCsv(...).collectwith the same options (columnsas a select) - 2.2Add
QuoteStyleand thewriteCsvoptions - 2.3Accept a plain
int(asint | Option[int]) fornRows,inferSchemaLengthandfloatPrecision - 2.4Write
tests/test_csv.nim: every option, a glob over two files, a glob whose files have different columns failing,columnsprojection,schemaOverridesand itsOthererror, and round trips (;with decimal comma,quoteStyle = Always,nullValue,floatPrecision); add it tonanuq.nimbleand.gitignore
3. Docs and integration
- 3.1Document the CSV options in the README; verify that
nimble test,nimble exampleand the existing CSV tests pass - 3.2Check that CI is green on the PR, including the Rust rebuild
Workflow follow-up
Revisions
e6c3502 Implement add-csv-options-and-scanFirst version: .openspec.yaml, design.md, proposal.md, specs/csv-io/spec.md, specs/native-bridge/spec.md, tasks.md
add-cumulative-and-shift Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 4/4
- Archive
Proposal
Why
Comparing a row with the rows before it is the heart of time-series work: day-to-day change, running totals, records so far, how long a streak lasts. Nanuq has over and rank but no shift, diff or cumulative functions, so a port of a "change since yesterday" query needs a self-join. The O'Reilly chapter 8 sections "Operations that accumulate" and the Packt window recipes stop here, and so does the 0.4 explainer (El Niño events are runs of consecutive warm seasons).
It is the second change of the 0.4 release.
What Changes
- Shifting and differences:
shift(n = 1, fillValue),diff(n = 1, nullBehavior)with aNullBehaviorpure enum (Ignore,Drop), andpctChange(n = 1). - Cumulative functions:
cumSum,cumProd,cumMin,cumMax,cumCount, each withreverse = false. - Runs and peaks:
rleId(an id that grows by one each time the value changes),peakMax,peakMin. - More aggregations:
product,mode,argMin,argMax,skew(bias = true),kurtosis(fisher = true, bias = true).
Capabilities
New Capabilities
cumulative-functions: shift, diff, pctChange, cumulative functions, runs and peaks.
Modified Capabilities
expressions: more aggregations (product, mode, argMin, argMax, skew, kurtosis).
Differences from Polars
shiftwith a fill value is one proc with a namedfillValue(Python'sfill_value, Rust'sshift_and_fill).diff'snullBehavioris theNullBehaviorpure enum (Python takes the strings "ignore" and "drop").nis anint(Rust and Python also accept an expression); that covers every use in the Polars docs and books.rle(which returns a Struct) waits for Struct columns in 0.5;rleIdis here.
Impact
src/rust/src/lib.rs:NqUnarygrows (cumulative functions, product, mode, argMin, argMax, rleId, peaks),nq_expr_shift,nq_expr_diff,nq_expr_pct_change,nq_expr_moment;src/nanuq/ffi.nim,src/nanuq.nim.- New
tests/test_cumulative.nim.
Spec changes
cumulative-functions modified
Shifting
e.shift(n = 1) SHALL move values down by n rows (up when n is negative), filling the rows left empty with null, or with fillValue when it is given. Inside over, the shift SHALL happen within each group.
let df = newDataFrame:
month: ["Jan", "Feb", "Mar", "Apr"]
anomaly: [0.5, 0.8, 1.2, 0.9]
echo df.withColumns(col.anomaly.shift.alias("before"),
col.anomaly.shift(-1, fillValue = 0.0).alias("after"))
TBD
- WHEN
col.x.shift.over(col.g)runs on groups a = 1, 2 and b = 3, 4 - THEN the result is null, 1, null, 3
Differences
e.diff(n = 1, nullBehavior = NullBehavior.Ignore) SHALL subtract from each value the value n rows above, with null where there is none; NullBehavior.Drop SHALL leave out those rows. e.pctChange(n = 1) SHALL return the relative change from the value n rows above.
let df = newDataFrame:
year: [2021, 2022, 2023, 2024]
temp: [14.8, 14.9, 15.1, 15.3]
echo df.select(col.year, col.temp.diff.round(2).alias("diff"),
col.temp.pctChange.round(4).alias("pct"))
TBD
- WHEN
diff(nullBehavior = Drop)runs on 1, 4, 9 - THEN the result is 3, 5
Cumulative functions
cumSum, cumProd, cumMin, cumMax and cumCount SHALL return the running sum, product, minimum, maximum and count of non-null values from the first row, or from the last row with reverse = true.
let df = newDataFrame:
rain: [3, 0, 7, 2]
echo df.withColumns(col.rain.cumSum.alias("total"), col.rain.cumMax.alias("wettest"),
col.rain.cumSum(reverse = true).alias("still_to_come"))
TBD
- WHEN
cumMaxruns on 3, 1, 5, 2 - THEN the result is 3, 3, 5, 5
- WHEN
cumCountruns on 1, null, 3 - THEN the result is 1, 1, 2
Runs and peaks
e.rleId SHALL number the runs of equal consecutive values, starting at 0 and growing by one each time the value changes. peakMax and peakMin SHALL be true at local maxima and minima.
let df = newDataFrame:
season: ["DJF", "JFM", "FMA", "MAM", "AMJ", "MJJ"]
warm: [true, true, false, false, true, true]
echo df.withColumns(col.warm.rleId.alias("run"))
TBD
- WHEN rows are grouped by
rleIdof true, true, false, true and counted - THEN the runs have lengths 2, 1 and 1
expressions modified
Shape and position aggregations
Expressions SHALL have the aggregations product, mode (every most frequent value, in order of appearance), argMin and argMax (the row index of the first minimum or maximum), skew(bias = true) and kurtosis(fisher = true, bias = true).
let df = newDataFrame:
year: [2020, 2021, 2022, 2023]
oni: [0.5, -1.0, -0.9, 1.9]
echo df.select(col.oni.argMax.alias("warmest_row"),
col.oni.argMin.alias("coldest_row"), col.oni.skew.round(3).alias("skew"))
TBD
- WHEN
productruns on 2, 3, 4 - THEN the result is 24
- WHEN
moderuns on 1, 2, 2, 3, 3 - THEN the result holds 2 and 3
Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Ranking, Filtering inside expressions, Boolean aggregations, Entropy, Row count expression, Several window keys and selector concatenation, Null-aware comparisons and closeness, More expression functions
Tasks
1. Implementation
- 1.1
shift,diff(withNullBehavior),pctChange - 1.2Cumulative functions with
reverse,rleId,peakMax,peakMin - 1.3
product,mode,argMin,argMax,skew,kurtosis - 1.4Tests in
tests/test_cumulative.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
570d956 Nanuq 0.4, changes 1-7: math, cumulative, rolling, value functions, horizontal, reshaping, time groupingFirst version: proposal.md, specs/cumulative-functions/spec.md, specs/expressions/spec.md, tasks.md
add-database-io Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 2/2
- Archive
Proposal
Why
Reading query results from a database and writing frames back is common enough that the 0.6 book map counts 10 sections needing read_database, read_database_uri or write_database (user guide io/database, O'Reilly ch6, Packt ch2 and ch11, the escobar-west cookbook ch9), and most use SQLite. Python Polars goes through SQLAlchemy, ADBC or ConnectorX, which have no Nim counterpart, but Nim's db_connector package (the database modules that left the standard library) talks to SQLite directly.
It is the seventh change of the 0.6 release and takes the "databases" part of the coverage roadmap (Excel and databases in "More IO").
What Changes
- New optional module
nanuq/database(likenanuq/datamancer, only it needs the extra packagedb_connector). readDatabase(query, connection, schemaOverrides)for an open SQLiteDbConn: types from the values (INTEGER → Int64, REAL → Float64, TEXT → String, BLOB → Binary; a column of only nulls from its declared type).readDatabaseUri(query, uri, schemaOverrides)withsqlite:///pathURIs.writeDatabase(df, tableName, connection, ifTableExists = Fail | Replace | Append), creating the table from the frame's types, in one transaction; returns the rows written.
Capabilities
New Capabilities
database-io: reading and writing SQLite databases.
Differences from Polars
- SQLite only. Python accepts any SQLAlchemy, ADBC or DBAPI connection and URIs for PostgreSQL, MySQL and others through ConnectorX; PostgreSQL and MySQL through db_connector are a possible follow-up (they return values as text without types).
- No
execute_options,iter_batches,batch_sizeorinfer_schema_length; noenginechoice. ifTableExistsis an enum (Python strings"fail","replace","append"), and there is noengine_options.- Dates, times and datetimes are written as ISO text (SQLite has no date type), as Python does through SQLAlchemy.
Impact
- New
src/nanuq/database.nim; not imported bynanuqitself. - New
tests/test_database.nim; CI installsdb_connectorwith Datamancer.
Spec changes
database-io modified
Writing to a database
writeDatabase(df, tableName, connection, ifTableExists = IfTableExists.Fail) in nanuq/database SHALL write the frame's rows to a SQLite table, creating it with column types from the frame (integers and booleans INTEGER, floats REAL, Binary BLOB, the rest TEXT), and return the number of rows written. An existing table SHALL raise ValueError with Fail, be dropped first with Replace, and receive the rows with Append.
import nanuq/database, db_connector/db_sqlite
let db = open(":memory:", "", "", "")
let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380]))
echo df.writeDatabase("bears", db)
echo df.writeDatabase("bears", db, IfTableExists.Append)
TBD
- WHEN a frame is written to an existing table with
IfTableExists.Fail - THEN
ValueErroris raised and the table is unchanged
Reading from a database
readDatabase(query, connection, schemaOverrides = []) SHALL run a query on an open SQLite connection and return its rows, with INTEGER values as Int64, REAL (or mixed numbers) as Float64, TEXT as String and BLOB as Binary, and a column of only nulls typed from its declared type. readDatabaseUri(query, "sqlite:///path") SHALL open the database for the query and close it.
import nanuq/database, db_connector/db_sqlite
let db = open(":memory:", "", "", "")
discard newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.5, 380.0])).writeDatabase("bears", db)
echo readDatabase("select bear, kg * 2 as double from bears where kg > 400", db)
TBD
- WHEN the query names a table that does not exist
- THEN
IOErroris raised
- WHEN
readDatabaseUrigets apostgres://URI - THEN
ValueErroris raised
Tasks
1. Implementation
- 1.1
src/nanuq/database.nim:readDatabase,readDatabaseUri,writeDatabase,IfTableExists - 1.2Tests in
tests/test_database.nim; CI installs db_connector; spec examples pass; CHANGELOG
Revisions
4ea5dad 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6First version: proposal.md, specs/database-io/spec.md, tasks.md
add-datamancer-interop Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 6/6
- Archive
Proposal
Why
Datamancer is Nim's pure-Nim dataframe, and ggplotnim plots only Datamancer DataFrames. Today moving data across means one toSeq per column and spelling out every column name (see the "Plotting with ggplotnim" post). A conversion both ways lets Datamancer code hand heavy queries to Polars and get the result back, and makes plotting a Nanuq result a single call.
This takes up the BACKLOG.md entry "Datamancer interop both ways" (Ecosystem).
What Changes
- New optional module
nanuq/datamancer(it importspkg/datamancer; Nanuq itself does not require Datamancer): toDatamancer(df): datamancer.DataFramecopies every column. Integer columns becomeintcolumns, floatsfloat, booleansbool, stringsstring. Any other dtype (dates, categoricals, …) becomes astringcolumn formatted by Polars, astoSeq(…, string)does.- A column with nulls becomes a Datamancer object column whose missing entries are Datamancer's
nullvalues, sodrop_nullandtoTensor(…, dropNulls = true)work on it. Null-free columns keep their native type. fromDatamancer(dm): nanuq.DataFramecopies every column back:intto i64,floatto f64,bool,stringto str, constant columns repeated to the frame's length, and object columns holding one kind of value (plus nulls) to that dtype with nulls. Mixed object columns raiseNanuqError.- Column order and names are kept both ways.
- The "Plotting with ggplotnim" post uses
toDatamancerinstead of onetoSeqper column, and keeps its explanation of what happens underneath. - CI installs Datamancer for the tests.
Capabilities
New Capabilities
datamancer-interop: converting DataFrames between Nanuq and Datamancer.
Modified Capabilities
None.
Differences from Polars
- Python has the same idea for pandas:
df.to_pandas()andpl.from_pandas(pdf). Nanuq follows those names in camelCase, as a function in a separate module (Nim cannot add methods, and Datamancer stays optional, like pandas is for Polars). - Nulls.
to_pandasturns nulls intoNaNorNonedepending on the dtype; Nanuq uses Datamancer'snullvalues in an object column, Datamancer's own way to mark missing data. - Rust has no equivalent.
- Copies. Like
to_pandaswithout pyarrow-backed columns, the data is copied.
Impact
src/nanuq/datamancer.nim(new). No bridge change: it is built ontoSeqandseries, including theirOptionvariants.tests/test_datamancer.nim(new);.github/workflows/ci.ymlinstalls Datamancer in the test job.docs/blog/plotting_with_ggplotnim.nim, README (one line on the module).
Spec changes
datamancer-interop modified
Purpose: Converting DataFrames between Nanuq and Datamancer (nanuq/datamancer), so Datamancer
and ggplotnim code can use Polars for queries. Datamancer stays an optional dependency.
To Datamancer
toDatamancer SHALL copy every column, in order and with its name, into a Datamancer DataFrame: integers as int, floats as float, booleans as bool, strings as string, and any other dtype as string formatted by Polars.
- WHEN
penguins().dropNulls().toDatamanceris called - THEN the result has 333 rows, the same column names in order, and
body_mass_gis anintcolumn
Nulls to Datamancer
A column with nulls SHALL become an object column whose missing entries are Datamancer null values and whose other entries hold the values.
- WHEN
penguins().toDatamanceris called - THEN
body_mass_gis an object column with 2nullvalues, anddrop_nullon it leaves 342 rows
From Datamancer
fromDatamancer SHALL copy every column back in order: int to i64, float to f64, bool to bool, string to str, constant columns repeated, and object columns of one value kind plus nulls to that dtype with nulls. Other object columns SHALL raise NanuqError.
- WHEN a Nanuq DataFrame is converted with
toDatamancerand back withfromDatamancer - THEN it has the same shape, columns, dtypes (for i64, f64, bool, str) and null counts
- WHEN a Datamancer object column holds both an int and a string
- THEN
fromDatamancerraisesNanuqErrornaming the column
Optional dependency
Importing nanuq SHALL NOT require Datamancer; only importing nanuq/datamancer does.
- WHEN a program imports only
nanuqon a machine without Datamancer - THEN it compiles
Tasks
1. Module
- 1.1Add
src/nanuq/datamancer.nim(importingpkg/datamancer) withtoDatamancer, usingtoSeqfor null-free columns andOptionreads for columns with nulls; verify with tests for dtypes, column order and nulls - 1.2Add
fromDatamancer, handling int, float, bool, string, constant and object columns; verify with tests for a round trip and a mixed object column - 1.3Add
tests/test_datamancer.nimtonimble testand install Datamancer in the CI test job; verifynimble testpasses, and that the other tests still compile without Datamancer installed
2. Docs
- 2.1Rewrite the conversion in "Plotting with ggplotnim" with
toDatamancer(keeping the explanation of the copy and of nulls); verify the post renders and republish its artifact - 2.2Mention
nanuq/datamancerin the README - 2.3Check CI is green on the PR
Workflow follow-up
Revisions
ed08e02 Archive the dev-log index, HTML tables and Datamancer interop changesFirst version: .openspec.yaml, proposal.md, specs/datamancer-interop/spec.md, tasks.md
add-datatype-and-cast Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 10/10
- Archive
Proposal
Why
Nanuq has no Nim-side notion of a data type. dtype(df, col) returns Polars' display string ("i64", "str"), so code has to compare strings, and nothing can ask Polars to convert a column. Several parts of the 0.2 plan need a real type value first: cast, dtype column selectors, and CSV schema overrides. This change adds that type value, schemas, and casting, so the other 0.2 changes can build on it.
This change takes up the casting part of the BACKLOG.md entry "More expressions" (API). The rest of that entry stays in the backlog. It is the first change of the 0.2 release (see the Polars coverage map, areas "Data types" and "Casting and types").
What Changes
- New
DataTypevalue with akind(DataTypeKind) covering Polars' primitive dtypes: Boolean, Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64, String and Null. Dtypes Nanuq does not model yet (Date, List, Categorical, ...) come back as kinddkOtherand keep Polars' name. - Constants named as in Polars:
Boolean,Int8...UInt64,Float32,Float64,String,Null.$gives Polars' short name ("i64"), as today. - Predicates
isInteger,isSignedInteger,isUnsignedInteger,isFloat,isNumeric. - BREAKING:
dtype(df, col)returns aDataTypeinstead of a string. Code that compares with strings (df.dtype("a") == "i64") must compare with constants (== Int64) or use$. - New
schema(df)andcollectSchema(lf): the column names and types, in order, as aSchema(anOrderedTable[string, DataType]). Newdtypes(df). - New
cast,strict = trueby default. The target is a Nim type where one is enough:col("a").cast(int32),df.cast(float64)(all columns). Named columns of a frame takeDataTypevalues, since a list can't hold different typedescs:df.cast({"a": Int32, "b": Float32}). Every form also accepts aDataType. - New
dataType(T)maps a Nim type to itsDataType:int8..int64,uint8..uint64,float32,float64,bool,string;intandfloatmap toInt64andFloat64, matching howseriesbuilds them. - The C ABI version moves to
0.2.0-dev. Untillib-v0.2.0is released, building from a checkout compiles the Rust library from source (prebuilt archives are only fetched for released versions).
Capabilities
New Capabilities
data-types: theDataTypevalue, schemas, and casting.
Modified Capabilities
native-bridge: the enums that must keep the same order in Rust andffi.nimnow includeNqDtype.
Differences from Polars
Expected differences from Polars' Rust and Python APIs:
- One value type, not a class hierarchy. Python has classes (
pl.Int64,pl.Datetime("ms")) underpl.DataType; Rust has theDataTypeenum with data in some variants. Nim gets an object variant with akindenum, which can grow parameters (time unit, inner type) later. The constants keep Polars' names, sodf.cast({"a": Int32})reads like Python. - Nim types as cast targets. Polars only takes its own dtypes. Nanuq also takes Nim types (
col("a").cast(int32)), liketoSeq(df, "a", int)does for reads.dtypeandschemastill returnDataTypevalues: a Nim type can't be returned at run time. - Unmodelled dtypes. Polars knows every dtype. Nanuq maps the ones it does not model yet to
dkOtherwith Polars' name, and refuses tocastto them. - No 128-bit integers, no Decimal.
Int128,UInt128andDecimalare left out (they need extra Polars features); they would read asdkOther. $is Polars' short name. Python printsInt64; Rust'sDisplayprintsi64. Nanuq follows Rust, which is also what the table header shows in both. Nim names (int64,string) were considered and dropped:$dfis rendered by Polars, so the tables would disagree with$or need their dtype row rewritten.- Schema type. Python's
pl.Schemais an ordered mapping; Nanuq uses Nim'sOrderedTable[string, DataType]. Python'sdf.schemais a property; in Nim it is a proc,df.schemareads the same. castis a Nim keyword. Method-call syntax works (col("a").cast(int32),df.cast(float64)), but the prefix form needs backticks:cast(col("a"), int32).- Frame cast arguments. Python's
df.cast({"a": pl.Int32})takes a dict; Nim takes anopenArray[(string, DataType)], written with the same braces:df.cast({"a": Int32}). - Strict default. Like Python and Rust's
strict_cast,castfails when a value can't be converted;strict = falseturns those values into nulls, like Polars. - No builders for other widths.
seriesstill builds int64, float64, bool and string columns; other widths come fromcast. Reading any integer column asintand any numeric column asfloatworks as today. - Names follow Polars in camelCase:
collect_schema→collectSchema,is_integer→isInteger,is_signed_integer→isSignedInteger,is_unsigned_integer→isUnsignedInteger,is_float→isFloat,is_numeric→isNumeric.
Impact
src/rust/src/lib.rs: a#[repr(C)]NqDtypeenum,nq_df_column_dtype_kind,nq_lf_collect_schema(an empty DataFrame carrying the schema),nq_expr_cast,nq_lf_cast.nq_df_column_dtype(the string) stays and namesdkOtherdtypes.Cargo.tomladds Polars featuresdtype-i8,dtype-i16,dtype-u8,dtype-u16and moves to version0.2.0-dev. The Rust library is rebuilt, so the first CI run takes about 10 minutes.src/nanuq/ffi.nim,src/nanuq.nim: the matching declarations and API; importsstd/tables.src/nanuq/datamancer.nimand the HTML table switch from dtype strings toDataType.tests/: dtype string comparisons become constant comparisons; new tests for schemas and casts. The dev-log post "How Nanuq works" still printsdtypewithecho, so its output is unchanged.README.md: the API list mentionsschemaandcast.
Spec changes
data-types modified
DataType values
The API SHALL provide a DataType value with a kind of type DataTypeKind covering Boolean, Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64, String and Null, plus dkOther carrying Polars' name for any other dtype. It SHALL export constants with Polars' names (Int64, String, ...), ==, $ returning Polars' short name, and the predicates isInteger, isSignedInteger, isUnsignedInteger, isFloat and isNumeric. dtype(df, col) SHALL return a DataType.
- WHEN a DataFrame is built from a Nim
seq[int]columna - THEN
df.dtype("a") == Int64and$df.dtype("a") == "i64"
- WHEN a column has a dtype Nanuq does not model
- THEN its
kindisdkOtherand$returns Polars' name for it
- WHEN
isNumericis called onUInt8,Float32andString - THEN it returns true, true and false
Schemas
The API SHALL return the column names and dtypes of a DataFrame (schema) and of a LazyFrame without collecting it (collectSchema) as a Schema, an OrderedTable[string, DataType] in column order, and the dtypes alone with dtypes.
- WHEN
schemais called on a DataFrame with columnsa(i64) andb(str) - THEN the keys are
a,bin that order and the values areInt64,String
- WHEN
collectSchemais called on a LazyFrame that adds(col("a") * 1.5).alias("c") - THEN the schema has
cwithFloat64, and the query is not executed
Casting
The API SHALL cast expressions (e.cast(target, strict = true)), all columns of a DataFrame or LazyFrame (cast(target, strict = true)), where target is a Nim type or a DataType, and named columns (cast({"a": Int32}, strict = true)) with DataType values. A strict cast SHALL raise NanuqError (when the query runs) if a value cannot be converted; a non-strict cast SHALL turn such values into nulls. Casting to a dkOther dtype SHALL raise NanuqError.
- WHEN
df.cast({"a": Int32})runs on an i64 column - THEN
dtype("a") == Int32andtoSeq(df, "a", int)returns the same values
- WHEN
col("a").cast(float32)is selected from an i64 column - THEN the result column has dtype
Float32
- WHEN a string column holding "1" and "x" is cast to
Int64withstrict = true - THEN
NanuqErroris raised
- WHEN the same column is cast with
strict = false - THEN the result is 1 and null
Nim types map to DataType
dataType(T) SHALL map int8 to int64, uint8 to uint64, float32, float64, bool and string to their dtypes, int to Int64 and float to Float64. Other types SHALL not compile.
- WHEN
dataType(int)is evaluated - THEN it equals
Int64, the dtypeseriesbuilds fromseq[int]
- WHEN
col("a").cast(seq[int])is compiled - THEN compilation fails
Unchanged in this spec: DataType constants and predicates, Full-range UInt64
native-bridge modified
Nim declarations mirror the C ABI
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release
Design
Design
Context
nq_df_column_dtype returns col.dtype().to_string(). Nim exposes it as dtype(df, col): string, and datamancer.nim, the HTML table and the tests compare those strings. Expressions cross the C ABI as opaque Expr pointers, and enums (NqBinOp, NqUnary) as #[repr(C)] integers mirrored in ffi.nim. Polars is built with default-features = false and lazy, csv, fmt, so only 32 and 64 bit integers are compiled in.
Goals / Non-Goals
Goals:
- A Nim type value that the rest of 0.2 (selectors, CSV schema overrides) can pass through the ABI.
- Room to add parameterized dtypes (Datetime with unit and zone, List with an inner type) in 0.3 and later without breaking user code.
caston expressions and frames with Polars' strict semantics.
Non-Goals:
- Temporal, nested, categorical and decimal dtypes (0.3 and 0.5 in the coverage map).
- Building or reading columns in widths other than int64 / float64 (use
cast). - Dtype selectors (
cs.numeric()): they come with the column selectors change.
Decisions
DataType is an object variant with a kind enum
type
DataTypeKind* = enum
dkBoolean, dkInt8, dkInt16, dkInt32, dkInt64, dkUInt8, dkUInt16, dkUInt32,
dkUInt64, dkFloat32, dkFloat64, dkString, dkNull, dkOther
DataType* = object
case kind*: DataTypeKind
of dkOther: name*: string # Polars' name, e.g. "date", "list[i64]"
else: discard
const Int64* = DataType(kind: dkInt64) # and so on for each primitive kind
== compares kinds (and the name for dkOther). $ returns Polars' short name.
- Why: Polars' Rust
DataTypeis an enum with data in some variants; an object variant is the Nim equivalent, and later kinds (dkDatetimewithunitandzone,dkListwith aninner: ref DataType) are added as new branches without changing existing code. - Alternative: a plain enum
DataType. Simplest today, but turning it into an object for Datetime or List would break every user of it. - Alternative: a
ref objecthierarchy like Python's classes. More allocation andofchecks, with no gain over a variant. - Constants use Polars' names (
Int64,String). They are exported fromnanuq; a clash with a user symbol is resolved by qualifying, e.g.nanuq.String.
Dtypes cross the ABI as a code
#[repr(C)] enum NqDtype { Boolean = 0, Int8, ..., Null, Other }, mirrored in ffi.nim in the same order as DataTypeKind. nq_df_column_dtype_kind(df, name) -> i32 returns the code (or -1 on error). For Other, Nim also calls the existing nq_df_column_dtype for the name. Casting passes a code; Other is rejected in Nim before any call.
- Why: fits the existing enum style, and a code is enough until dtypes have parameters. A parameterized dtype will need a small struct or a string form (Polars can parse dtype strings); that is decided when the first one arrives.
Schemas reuse DataFrame accessors
schema(df) loops over columns(df) and asks each dtype (one call per column, not per row). collectSchema(lf) calls nq_lf_collect_schema, which resolves the plan's schema (LazyFrame::collect_schema) and returns DataFrame::empty_with_schema; Nim then reads it with schema. Nothing is computed beyond schema resolution.
- Why: no new type to free and no array-of-structs across the boundary.
Cast functions
nq_expr_cast(e, code, strict: bool) -> *mut Exprusesstrict_castorcastwith non-strict options in Polars 0.55.nq_lf_cast(lf, names, codes, n, strict) -> *mut LazyFramecasts the named columns (LazyFrame::castwith a map). Casting all columns is done in Nim ascast(all columns)by passing every name from the schema, so one Rust function covers both forms. DataFrame versions are eager shortcuts over the lazy one, as for the other verbs.- Nim names:
cast(a keyword, usable with method-call syntax, see the proposal).
Nim types as cast targets
cast has a typedesc overload next to the DataType one:
proc cast*(e: Expr, T: typedesc, strict = true): Expr = e.cast(dataType(T), strict)
dataType(T) is resolved at compile time (when T is int8: Int8 ...), and an unsupported type (an object, seq) is a compile error. Named frame casts stay on DataType ({"a": Int32}), because an openArray needs one element type and typedescs exist only at compile time; dataType(int32) gives the same value.
- Why: reads already take Nim types (
toSeq(df, "a", int)), so writes and casts should too; the Polars names stay available for run-time values. - Later:
seq[T]can map to List andDateTimeto Datetime, with aDataTypefor the cases a Nim type can't express (time unit, time zone).
ABI version during 0.2
Cargo.toml moves to 0.2.0-dev with this change. ffi.nim already treats -dev versions as development builds (no prebuilt download; local or cargo build). The other 0.2 changes keep 0.2.0-dev, and lib-v0.2.0 is released once, when 0.2 is complete, so there is one release cycle for the whole slice instead of one per change.
Risks / Trade-offs
- Breaking
dtype. Comparisons with strings stop compiling (aDataTypeis not a string), which is loud rather than silent. Nanuq is pre-1.0 with no known users outside the repo; the CHANGELOG calls it out. - Binary size. Four small dtype features add a little code to an already large static library. Accepted.
- Constant names may shadow.
String,Boolean,Nullare common words. Nim is case-sensitive on the first letter, so they do not clash withstringorbool.
Tasks
1. Bridge
- 1.1Move
src/rust/Cargo.tomlto version0.2.0-devand add Polars featuresdtype-i8,dtype-i16,dtype-u8,dtype-u16; verifycargo build --releasepasses andffi.nimfalls back to the local build - 1.2Add
#[repr(C)] NqDtypewith conversions to and from PolarsDataType, andnq_df_column_dtype_kind; mirror both inffi.nim - 1.3Add
nq_lf_collect_schema(empty DataFrame with the resolved schema),nq_expr_castandnq_lf_cast(strict flag); mirror them inffi.nim; verifycargo build --releasepasses
2. Nim API
- 2.1Add
DataTypeKind,DataType, the constants,==,$and the predicates; verify with unit tests that need no DataFrame - 2.2Change
dtype(df, col)to returnDataType(name lookup fordkOther); updatedatamancer.nim, the HTML table and the tests that compare dtype strings; verifynimble testpasses - 2.3Add
Schema,schema(df),dtypes(df)andcollectSchema(lf); verify column order and that a lazy schema does not execute the query - 2.4Add
dataType(T)for the supported Nim types; verify the mapping, and with a compile-time check that an unsupported type does not compile - 2.5Add
caston Expr, and on LazyFrame and DataFrame for all columns (Nim type orDataType) and for named columns (DataType); verify narrowing, a Nim-type target, strict failure, non-strict nulls and thedkOthererror
3. Docs and integration
- 3.1Update README "What is there" with
DataType,schemaandcast; verifynimble examplepasses and the dev-log post output is unchanged - 3.2Check that CI is green on the PR, including the one-off Rust rebuild
Workflow follow-up
Revisions
e7c3da0 Archive add-datatype-and-cast; BACKLOG and CHANGELOGFirst version: .openspec.yaml, design.md, proposal.md, specs/data-types/spec.md, specs/native-bridge/spec.md, tasks.md
f2217bf add-datatype-and-cast: CI green, tick task 3.2tasks.mdadd-devlog-index Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 7/7
- Archive
Proposal
Why
The GitHub Pages root redirects to the latest dev-log post, so the other posts can only be found through the README. There are three posts now and more will follow.
This takes up the BACKLOG.md entry "Blog index page" (Docs).
What Changes
- New nimib page
docs/index.nim, rendered to the site root with the Nanuq theme. It lists every post indocs/blog, newest first, with its date, title and a one-line summary, each linking to the post. - The index is built from the rendered posts, so a new post needs no edit to the index: the date and link come from the post's dated file name (
2026-10-27-…html), the title from its<title>, and the summary from a<meta name="description">that the theme writes. useNanuqThemegets asummaryparameter for that meta tag. The three existing posts get a summary.- CI renders the posts, then the index, and publishes the index as the site root instead of the redirect. Posts keep their URLs under
blog/. - The README points to the index as well as the posts.
Capabilities
New Capabilities
dev-log: how the dev log is organised and published (posts, index, theme).
Modified Capabilities
ci: the site root is the index instead of a redirect.
Differences from Polars
None: this is about Nanuq's own docs site, not the Polars API.
Impact
docs/index.nim(new),docs/nanuqtheme.nim, the three posts indocs/blog/..github/workflows/ci.yml(docs job),README.md.- No library code changes.
Spec changes
ci modified
Tests, example and dev log
Unchanged in this spec: Build Rust only when the crate changes, Skip CI for non-code changes, Lib version follows the crate sources, Fast linking
dev-log modified
Purpose: The Nanuq dev log: dated nimib posts in docs/blog, an index page, and the Nanuq theme
they share. It is published with GitHub Pages and is separate from the official
documentation that will come later.
Index of posts
The site root SHALL be an index page listing every rendered post in docs/blog, newest first, each with its date, title, one-line summary and a link to the post. Adding a post SHALL NOT require editing the index.
- WHEN a post
docs/blog/x.nimwriting2026-11-02-x.htmlis added and CI renders the site - THEN the index lists it first, dated 2 November 2026, with its title and summary
- WHEN a post does not set a summary
- THEN the index still lists it, with date and title only
Dated post files
Each post SHALL render to a file in docs/blog named YYYY-MM-DD-<slug>.html, and its URL SHALL stay the same once published.
- WHEN the index is introduced
- THEN the existing post URLs under
blog/keep working
Unchanged in this spec: Polars coverage page, OpenSpec page, Review mode, Source files
Tasks
1. Theme and posts
- 1.1Add a
summaryparameter (default empty) touseNanuqThemethat writes<meta name="description">; verify a post renders with the tag - 1.2Give the three posts a one-line summary; verify each renders
2. Index page
- 2.1Add
docs/index.nim: scandocs/blog/*.html, read date and slug from the file name, title from<title>, summary from the meta tag; render a newest-first list with the Nanuq theme todocs/index.html; verify locally after rendering the posts - 2.2Check the index at phone width and in dark mode
3. CI and README
- 3.1In the docs job, render the index after the posts and publish it as
_site/index.html, with relative links intoblog/; drop the redirect; verify the uploaded Pages artifact on the PR - 3.2Point the README's Documentation section to the index; verify the links
- 3.3Check CI is green on the PR
Workflow follow-up
Revisions
ed08e02 Archive the dev-log index, HTML tables and Datamancer interop changesFirst version: .openspec.yaml, proposal.md, specs/ci/spec.md, specs/dev-log/spec.md, tasks.md
add-dynamic-group-by Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 4/4
- Archive
Proposal
Why
Time series are grouped by calendar windows (monthly totals, weekly means, the three months around each month) and matched by nearest time (the reading at or before each event). Polars does this with group_by_dynamic, rolling and join_asof. Without them a Nanuq user has to truncate dates and join on them, which can't express overlapping windows or "the last value before". The O'Reilly chapters 1 and 13 and the user guide's time-series pages stop on group_by_dynamic (4 sections), and the 0.4 explainer needs joinAsof to line up El Niño seasons with monthly temperatures.
It is the seventh change of the 0.4 release.
What Changes
groupByDynamic(indexColumn, every, period, offset, includeBoundaries, closed, label, groupBy, startBy)on DataFrame and LazyFrame, followed byagg.LabelandStartByare pure enums; intervals are std/times intervals or Polars duration strings.rolling(indexColumn, period, offset, closed, groupBy), the rolling group-by: one window per row, followed byagg.joinAsof(other, on | leftOn + rightOn, by | byLeft + byRight, strategy, suffix, tolerance, allowExactMatches, checkSortedness, coalesce)with anAsofStrategypure enum (Backward,Forward,Nearest) and a tolerance given as an interval or a number.- Small parameter types with converters, so that optional parameters accept several types:
OptInterval(interval or string),JoinKey(name or expression),AsofTolerance(interval, string or number).
Capabilities
New Capabilities
temporal-grouping: dynamic and rolling group-by, as-of joins.
Differences from Polars
groupByinsidegroupByDynamicandrollingtakes expressions (groupBy = [col.site]); Python also takes names.joinAsof'son,leftOnandrightOntake one key each, as in Python.rollingon a frame is the rolling group-by, as in Python; the rolling expression functions arerollingMeanand friends.
Impact
src/rust/src/lib.rs:nq_lf_group_by_dynamic_agg,nq_lf_rolling_agg,nq_lf_join_asof;src/nanuq/ffi.nim;src/nanuq.nim(LazyGroupBygains the window options).- New
tests/test_timegroups.nim.
Spec changes
temporal-grouping modified
Dynamic group-by
groupByDynamic(indexColumn, every, period, offset, ...) on a DataFrame or LazyFrame SHALL group the rows of the sorted indexColumn into windows that start every every, span period (default every) and are shifted by offset, labelled as label says, and agg SHALL aggregate each window. Intervals SHALL be std/times intervals or Polars duration strings; groupBy SHALL group within the windows.
let df = newDataFrame:
day: [date(2026, 1, 1), date(2026, 1, 20), date(2026, 2, 3), date(2026, 3, 30)]
rain: [12, 3, 40, 7]
echo df.groupByDynamic("day", every = 1.months).agg(col.rain.sum).collect
TBD
- WHEN
groupByDynamic("day", every = 1.months, period = 3.months)aggregates monthly rows - THEN each window sums three months of rows
- WHEN
includeBoundaries = true - THEN the result has
_lower_boundaryand_upper_boundarycolumns
Rolling group-by
rolling(indexColumn, period, offset, closed = Right, groupBy) SHALL make one group per row, holding the rows whose indexColumn lies in the period up to that row's value (shifted by offset), and agg SHALL aggregate each group.
let df = newDataFrame:
day: [date(2026, 7, 1), date(2026, 7, 2), date(2026, 7, 5)]
rain: [4, 0, 10]
echo df.rolling("day", period = 3.days).agg(col.rain.sum.alias("rain_3d")).collect
TBD
- WHEN rows on July 1, 2 and 5 are grouped with
period = 3.days - THEN the July 5 group holds only the July 5 row
As-of join
joinAsof(other, on, ...) (or leftOn and rightOn) SHALL join each left row to one right row by a sorted key: the last one at or before it (Backward), the first one at or after it (Forward) or the closest (Nearest), only within tolerance when given and only among rows with equal by columns; rows without a match SHALL get nulls.
let events = newDataFrame:
day: [date(2026, 1, 15), date(2026, 3, 2)]
event: ["flood", "drought"]
let oni = newDataFrame:
month: [date(2026, 1, 1), date(2026, 2, 1), date(2026, 3, 1)]
oni: [1.8, 1.5, 1.1]
echo events.joinAsof(oni, leftOn = "day", rightOn = "month")
TBD
- WHEN the nearest earlier right row is 2 days before and
tolerance = 1.days - THEN the left row gets nulls
- WHEN
joinAsofis called withoutonand withoutleftOnandrightOn - THEN
ValueErroris raised
Unchanged in this spec: Group keys by name
Tasks
1. Implementation
- 1.1
groupByDynamicwithLabel,StartBy, intervals - 1.2
rollinggroup-by - 1.3
joinAsofwithAsofStrategy,by, tolerance - 1.4Tests in
tests/test_timegroups.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
570d956 Nanuq 0.4, changes 1-7: math, cumulative, rolling, value functions, horizontal, reshaping, time groupingFirst version: proposal.md, specs/temporal-grouping/spec.md, tasks.md
add-excel-io Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
Excel is how much tabular data arrives: the 0.6 book map counts 9 sections that need read_excel/write_excel (user guide io/excel, O'Reilly ch6 and ch13, Packt ch2), and BACKLOG.md "More IO" lists Excel. Rust Polars has no Excel support, so the crate adds two pure-Rust crates, compiled into the same static library as Polars: calamine to read and rust_xlsxwriter to write. Nothing outside the library is needed at run time.
It is the sixth change of the 0.6 release (the fifth, a formula macro, was dropped). It takes the Excel part of the BACKLOG.md entry "More IO".
What Changes
readExcel(path, sheetName, sheetId = 1, hasHeader, skipRows, columns, schemaOverrides): one sheet of an .xlsx, .xlsm, .xlsb, .xls or .ods file, with column types inferred from the cells (Boolean, Int64, Float64, Date, Datetime[ms], String).readExcelSheets(path): every sheet, by name.writeExcel(df, path, worksheet = "Sheet1", includeHeader, autofit, floatPrecision): one worksheet in a new .xlsx file.
Capabilities
New Capabilities
excel-io: reading and writing Excel workbooks.
Differences from Polars
- Python picks an engine (
calaminethrough the Python package fastexcel by default,openpyxl,xlsx2csv) and writes through the Python package xlsxwriter. Nanuq has one built-in reader (the calamine crate) and one writer (the rust_xlsxwriter crate). read_options={"skip_rows": n}andhas_headerbecomeskipRowsandhasHeaderparameters; there is noengine_options,infer_schema_lengthordrop_empty_rows.sheet_id = 0(all sheets as a dict) isreadExcelSheets;sheet_nameas a list is not supported.write_excelwrites a plain sheet: header in bold, numbers, booleans, dates and datetimes as Excel values, everything else as text. Python's table styles, conditional formats, sparklines, formulas, column widths and positions are left out, as is writing into an existing workbook.- Date cells at midnight read as Date, other date-times as Datetime[ms]; Python's fastexcel follows the cell format instead.
Impact
src/rust/Cargo.toml:calamine(featuredates),rust_xlsxwriter,chrono. The static library and the release archives grow by a few MB.src/rust/src/lib.rs,src/nanuq/ffi.nim:nq_read_excel,nq_excel_sheet_names,nq_write_excel.- New
tests/test_excel.nim.
Spec changes
excel-io modified
Writing Excel
writeExcel(df, path, worksheet = "Sheet1", includeHeader = true, autofit = false, floatPrecision = none(int)) SHALL write the frame to one worksheet of a new .xlsx file: a header row, then numbers, booleans, dates and datetimes as Excel values and other values as text; nulls SHALL be empty cells.
let path = getTempDir() / "bears.xlsx"
let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.5, 380.0]),
series("seen", @[date(2024, 3, 1), date(2024, 3, 9)]))
df.writeExcel(path, worksheet = "census")
echo fileExists(path)
TBD
- WHEN the target directory does not exist
- THEN
IOErroris raised
Reading Excel
readExcel(path, sheetName = "", sheetId = 1, hasHeader = true, skipRows = 0, columns = [], schemaOverrides = []) SHALL read one sheet (by name, else by position from 1) of an .xlsx, .xlsm, .xlsb, .xls or .ods file. Column types SHALL be inferred from the cells: Boolean, Int64 for whole numbers, Float64, Date for dates at midnight, Datetime[ms], else String; schemaOverrides SHALL cast columns and columns keep only those. readExcelSheets(path) SHALL read every sheet into a table by sheet name.
let path = getTempDir() / "bears.xlsx"
newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380]),
series("seen", @[date(2024, 3, 1), date(2024, 3, 9)])).writeExcel(path, worksheet = "census")
echo readExcel(path)
echo readExcel(path, sheetName = "census", skipRows = 1, hasHeader = false)
echo readExcelSheets(path).len
TBD
- WHEN
readExcel(path, sheetName = "nope")is called - THEN
IOErroris raised
- WHEN a frame of strings, integers, floats, booleans and dates is written and read back
- THEN the result equals the frame
Unchanged in this spec: Reading OpenDocument
Tasks
1. Implementation
- 1.1Crate: calamine reader with type inference, rust_xlsxwriter writer, sheet names
- 1.2
readExcel,readExcelSheets,writeExcel - 1.3Tests in
tests/test_excel.nim;nimble testandnimble specexamplespass; CHANGELOG; BACKLOG "More IO" updated
Revisions
4ea5dad 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6First version: proposal.md, specs/excel-io/spec.md, tasks.md
add-explainer-needs-0-5 Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 4/4
- Archive
Proposal
Why
Porting the 0.5 explainer "Above 4000" from Python to Nim (all 30 cells match py-polars) needed three workarounds: there is no frame-level fillNull(value) (df.fill_null(0)), frame filter takes one predicate where Python takes several, and groupBy has no maintainOrder parameter.
It is the twelfth change of the 0.5 release (#53).
What Changes
fillNull(value)andfillNull(strategy)on DataFrame and LazyFrame. A number fills the numeric columns (a float makes integer columns Float64), a string the String columns, a bool the Boolean ones, as Python'smatches_supertype=Truedefault does.filter(a, b, ...)on frames with several predicates, joined withand.groupBy(..., maintainOrder = ...)accepted for parity; Nanuq always keeps the first-seen group order.
Capabilities
Modified Capabilities
missing-values: frame-level null filling.frame-verbs: several filter predicates;maintainOrderongroupBy.
Differences from Polars
maintainOrder = falsestill keeps the order (Nanuq groups are always ordered).- No
matchesSupertype = falseoption.
Impact
src/nanuq.nimonly. Tests intests/test_nulls.nimandtests/test_verbs.nim.
Spec changes
frame-verbs modified
Several filter predicates
DataFrame and LazyFrame filter SHALL take several predicates, filter(a, b, ...), keeping the rows where all of them hold (Python's filter(a, b)).
let df = newDataFrame:
peak: ["Mont Blanc", "Monte Rosa", "Gran Paradiso"]
m: [4806, 4634, 4061]
italy: [true, true, true]
echo df.filter(col.m > 4500, col.italy)
- WHEN a row meets one predicate but not the other
- THEN it is dropped
Group order parameter
groupBy on DataFrame and LazyFrame SHALL accept maintainOrder (Python's maintain_order), with names or expressions; the groups SHALL keep the order their keys first appear whatever its value.
let df = newDataFrame:
country: ["CH", "IT", "CH"]
m: [4634, 4061, 4506]
echo df.groupBy("country", maintainOrder = true).agg(col.m.max)
- WHEN keys appear as CH, IT, CH and
maintainOrder = falseis passed - THEN the groups come out as CH, IT
Unchanged in this spec: Dropping and renaming columns, Row windows, Unique rows, Row index, Sorting by several keys, Sampling rows, Every n-th row, Frame interpolation, Casting by data type, Frame aggregations, Group-by shortcuts, Iterating over groups, Frame fillNan and select without a frame
missing-values modified
Filling nulls in whole frames
DataFrame and LazyFrame SHALL support fillNull(value), filling the columns the value fits (a number: numeric columns, where a float turns integer columns into Float64; a string: String columns; a bool: Boolean columns), and fillNull(strategy, limit) on every column (Python's df.fill_null).
let df = newDataFrame:
peak: ["Dom", "Täschhorn"]
m: [some(4545), none(int)]
first_ascent: [some(1858), none(int)]
echo df.fillNull(0)
- WHEN
fillNull(0.5)runs on a frame with an Int64 column with nulls - THEN that column becomes Float64 and its nulls hold 0.5
- WHEN
fillNull("x")runs on a frame with Int64 and String columns - THEN only the String column is filled
Unchanged in this spec: Nulls are read as Option, Plain reads refuse nulls, Inspecting nulls, Building columns with nulls, CSV null markers, Null expressions, Dropping rows with nulls, Interpolation, Null literal
Tasks
1. Implementation
- 1.1Frame
fillNull(value)andfillNull(strategy) - 1.2Frame
filter(a, b, ...) - 1.3
groupBy(..., maintainOrder) - 1.4Tests
Revisions
72a6989 0.5: explainer needs (add-explainer-needs-0-5)First version: proposal.md, specs/frame-verbs/spec.md, specs/missing-values/spec.md, tasks.md
add-explainer-needs-0-6 Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
The 0.6 explainer ("Move 37", go games) stores moves as Binary values, hashes board positions with 64-bit Zobrist keys, and reads raw lines from text files. Its Python draft (py-polars 2.1) needs a few things the first nine 0.6 changes did not cover.
It is the tenth change of the 0.6 release.
What Changes
bin.slice(offset, length),bin.head(n),bin.tail(n),bin.get(index, nullOnOob)(index may be an expression); reading one Binary cell returns its raw bytes, zero bytes included.str.toInteger(base = 10, dtype = Int64, strict = true), base 2 to 36 or a column.- UInt64 values above
high(int64):series("u", @[x'u64])andtoList(uint64)keep all 64 bits. readCsv/scanCsv:quoteChar(none(char)turns quoting off),encoding(CsvEncoding.Utf8Lossy) andnewColumns.
Capabilities
Modified Capabilities
binary-decimal: binary slicing and byte access,str.toInteger.csv-io:quoteChar,encoding,newColumns.data-types: UInt64 values abovehigh(int64).
Differences from Polars
quoteCharis anOption[char](Python:quote_char: str | None);encodingis an enum (Python strings"utf8","utf8-lossy").modon Decimal columns is not in the Polars 0.55 crate (py-polars 2.1 has it): cast to Float64 first. This is part of the known version drift.str.toIntegerneeds the Polars Int128/UInt128 types in the crate (a Polars 0.55 build requirement); they still read asDataTypeKind.Other.
Impact
src/rust/src/lib.rs:nq_expr_bin_slice,nq_expr_str_to_integer,nq_series_new_u64,nq_df_column_u64, CSV options; featuresstring_to_integer,dtype-i128,dtype-u128.src/nanuq.nim,src/nanuq/ffi.nim; newtests/test_explainer6.nim.
Spec changes
binary-decimal modified
Binary slicing and bytes
The bin namespace SHALL provide slice(offset, length), head(n), tail(n) (negative values count from the end) and get(index, nullOnOob = false), which gives the byte as UInt8; index MAY be an expression. Reading a single Binary cell as string SHALL give its raw bytes, zero bytes included.
let df = newDataFrame(series("m", @["\x03\x04\x10\x11", "ab"], Binary))
echo df.select(col("m").bin.get(1).alias("second"),
col("m").bin.slice(2, 2).bin.encode(BinaryEncoding.Hex).alias("tail_hex"))
TBD
- WHEN
bin.get(9, nullOnOob = true)reads a 4-byte value - THEN the result is null
Strings to integers
str.toInteger(base = 10, dtype = Int64, strict = true) SHALL parse strings as integers in base (2 to 36, or a column of bases); with strict = false, values that do not parse SHALL be null instead of raising.
let df = newDataFrame(series("k", @["zz", "10", "?"]))
echo df.select(col("k").str.toInteger(base = 36, strict = false))
TBD
- WHEN a value does not parse and
strictis true - THEN a
PolarsErroris raised
Unchanged in this spec: Binary data, Decimal data, Binary functions, Bitwise operations
csv-io modified
Quoting, encoding and new column names
readCsv and scanCsv SHALL take quoteChar = some('"') (none(char) turns quoting off), encoding = CsvEncoding.Utf8 (Utf8Lossy replaces invalid UTF-8 instead of raising) and newColumns, which renames the first columns.
import std/os
let path = getTempDir() / "lines.txt"
writeFile(path, "a \"quoted, line\nplain\n")
echo readCsv(path, separator = '\x01', hasHeader = false, quoteChar = none(char),
newColumns = ["line"])
TBD
- WHEN a line holds the byte 0xFF and
encoding = CsvEncoding.Utf8Lossy - THEN the line is read, with a replacement character
Unchanged in this spec: Scanning CSV, CSV read options, CSV write options, Reading CSV from a stream, Comment lines
data-types modified
Full-range UInt64
UInt64 columns SHALL keep all 64 bits between Nim and Polars: series(name, seq[uint64]) (with or without Option) and toList(uint64) SHALL handle values above high(int64).
let df = newDataFrame(series("key", @[1'u64, 9223372036854775809'u64]))
echo df.toList("key", uint64)
echo df.select(col("key").bitwiseXor)
TBD
- WHEN
series("u", [some(x), none(uint64)])is built - THEN the second value is null
Unchanged in this spec: DataType values, DataType constants and predicates, Schemas, Casting, Nim types map to DataType
Tasks
1. Implementation
- 1.1Crate: binary slicing,
str.to_integer(features), u64 series in and out, CSV quote/encoding - 1.2Nim:
bin.slice/head/tail/get, Binary cells as raw bytes,str.toInteger, UInt64,readCsvoptions - 1.3Tests in
tests/test_explainer6.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
fdee4e0 0.6: explainer needs (bin slicing, str.toInteger, full-range UInt64, CSV quoteChar/encoding/newColumns), book round 3 (readExcel headerRow/skipRows as fastexcel, GroupKeys), BACKLOG lean buildsFirst version: proposal.md, specs/binary-decimal/spec.md, specs/csv-io/spec.md, specs/data-types/spec.md, tasks.md
add-expr-essentials Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 13/13
- Archive
Proposal
Why
Nanuq's expressions can do arithmetic, comparisons and a handful of aggregations. Most real queries need a few more things: a conditional column (when/then/otherwise), a membership or range test, modulo and powers, a median or a quantile, filling nulls from the row above, and aggregates computed per group without collapsing rows (over). These are the expressions the 0.2 explainer post leans on, and the ones users reach for first after filter and groupBy.
This change takes up part of the BACKLOG.md entry "More expressions" (when/then/otherwise and window functions; string functions stay in the entry). It is the fourth change of the 0.2 release (see the Polars coverage map, area "Expressions"). The API choices for conditionals and fill strategies were made by Pietro on 2026-10-31 in the doc "Nanuq 0.2: API choices the explainer forces" (options A + D for conditionals, with the macro named choose; option A + B for fill strategies).
What Changes
- Conditionals, two spellings for one plan:
- The Polars chain:
when(cond).then(a).when(cond2).then(b).otherwise(c). Only the firstwhenneeds backticks, becausewhenis a Nim keyword. A chain withoutotherwisegives null for unmatched rows. A chain converts toExprautomatically. - A
choosemacro over Nim'sif/elif/else, which builds the same chain:
let size = choose:
if col("weight_kg") < 150: "cub"
elif col("weight_kg") < 500: "adult"
else: "chonk"
- Strings in
then,otherwiseand the macro branches are literal values, not column names. Usecol("x")for a column. - Membership and ranges:
isIn([1, 2, 3])(Nim values) orisIn(expr), withnullsEqual = false.isBetween(lower, upper, closed = Both), whereclosedis aClosedInterval(Both,Left,Right,None). - Arithmetic:
mod(Polars'%),div(Polars' floor division//),powand^,abs, unary-, andround(decimals = 0, mode = HalfToEven)with aRoundMode(HalfToEven,HalfAwayFromZero,ToZero). - Aggregations:
median,var(ddof = 1)(writtene.var),std(ddof = 1)(gainsddof),quantile(q, interpolation = Nearest)with aQuantileMethod(Nearest,Lower,Higher,Midpoint,Linear,Equiprobable), andlen(rows including nulls, unlikecount). - Null strategies:
fillNull(Forward),fillNull(strategy = Backward, limit = 2)with aFillNullStrategy(Forward,Backward,Mean,Min,Max,Zero,One), and the shortcutsforwardFill(limit)andbackwardFill(limit).fillNull(value)is unchanged. - Windows:
over("station"),over(["a", "b"])orover([expr])computes an expression per group and broadcasts it back to the rows. - New pure enums
ClosedInterval,QuantileMethod,FillNullStrategyandRoundMode, following theapi-conventionsspec. Polars featuresis_in,is_between,absandround_seriesare compiled in. The ABI stays0.2.0-dev.
Capabilities
New Capabilities
expressions: conditionals, membership and range tests, extra arithmetic and aggregations, null fill strategies and window expressions.
Modified Capabilities
native-bridge: the new enums join the ones that keep the same order in Rust andffi.nim.
Differences from Polars
Expected differences from Polars' Rust and Python APIs:
whenis backticked as a prefix call:when(cond)..then,.whenand.otherwiseare written as in Polars.chooseis Nanuq's own sugar and has no Polars counterpart. It builds the same plan, so$exprshows Polars'when/then/otherwise.- Strings are values in conditionals. Python's
.then("cub")means the column "cub", a known gotcha that needspl.lit("cub"). In Nanuq a string is a literal, as infillNull("x")today. - Operators: Python's
%,//and**become Nim'smod,divand^(orpow). They keep Polars' semantics, not Nim's:modanddivround towards negative infinity (-7 mod 3 == 2), where Nim's integermod/divtruncate. varis a Nim keyword, so it is writtene.var(orvar(e)).- Option values are enums:
closed = Left,method = Linear,fillNull(Forward). Rust'sFillNullStrategy::Forward(limit)carries the limit, but a pure enum can't carry data, solimitis a separate argument, as in Python. quantiletakes a float, not an expression, in this change. Its option is namedinterpolationas in Python (Rust's type isQuantileMethod), becausemethodis a Nim keyword and can't be a named argument.overtakes only the partition keys. Python'sorder_byandmapping_strategyare left for later.rounddefaults to half-to-even, as Rust Polars and Python Polars do (Nim'sroundrounds half away from zero).- Not in this change: string functions,
cum_*,rank,diff,shift,floor/ceil,log/exp, rolling windows,is_duplicated/is_unique,replace, andwhenwith several conditions per branch (when(a, b), writea and b). They stay in the coverage map. - Names follow Polars in camelCase:
is_in→isIn,is_between→isBetween,fill_null→fillNull,forward_fill→forwardFill,nulls_equal→nullsEqual.
Impact
src/rust/src/lib.rs:nq_expr_when_thenbuilds a whole chain from lists of conditions and values plus an optional otherwise.nq_expr_is_in,nq_expr_is_between,nq_expr_quantile,nq_expr_var_std(ddof),nq_expr_fill_null_strategy,nq_expr_over,nq_expr_roundandnq_expr_lit_series(forisInwith Nim values).- New
NqBinOpvaluesMod,FloorDivandPow; newNqUnaryvaluesAbs,Median,LenandNeg. Cargo.tomladds four features.src/nanuq/ffi.nimandsrc/nanuq.nimget the declarations, the four enums, the chain types with their converter toExpr, thechoosemacro and the procs.tests/test_expressions.nimcovers every function and option, and checks that the macro and the chain give the same plan.README.mdlists the new expressions.BACKLOG.mdkeeps "More expressions" for string functions only.
Spec changes
expressions modified
Conditional expressions
The API SHALL build conditional expressions with the chain when(cond).then(value) , optionally followed by more .when(cond).then(value) pairs and .otherwise(value). Rows matching no condition SHALL be null when there is no otherwise. A chain SHALL be usable wherever an Expr is expected. Values SHALL be expressions or Nim literals, and strings SHALL be literal values.
- WHEN
when(col("w") < 150).then("cub").when(col("w") < 500).then("adult").otherwise("chonk")is selected over weights 100, 300 and 900 - THEN the result is "cub", "adult" and "chonk"
- WHEN
when(col("w") < 150).then(1)is selected over weights 100 and 900 - THEN the result is 1 and null
choose macro
The API SHALL provide a choose macro that turns an if/elif/else expression with expression conditions into the same chain. A missing else SHALL mean null. Any other body SHALL fail to compile.
- WHEN a
chooseblock and the equivalent chain are built - THEN their
$strings are equal
- WHEN
choose(if col("collared"): "tracked" else: "free")is selected - THEN each row is "tracked" or "free"
Membership and ranges
Expr SHALL support isIn(values) for a list of Nim values or an expression, with nullsEqual = false, and isBetween(lower, upper, closed = Both) with a pure enum ClosedInterval (Both, Left, Right, None).
- WHEN
col("a").isIn([1, 3])is selected over 1, 2 and 3 - THEN the result is true, false and true
- WHEN
col("a").isBetween(1, 3, closed = Left)is selected over 1, 2 and 3 - THEN the result is true, true and false
Arithmetic operators
Expr SHALL support mod, div (floor division), ^ and pow, abs and unary -, with Nim literals on either side of a binary operator. mod and div SHALL follow Polars' floor semantics.
- WHEN
lit(-7) mod 3andlit(-7) div 3are evaluated - THEN the results are 2 and -3
- WHEN
col("a") ^ 2is selected over 3 - THEN the result is 9
Rounding
Expr SHALL support round(decimals = 0, mode = HalfToEven) with a pure enum RoundMode (HalfToEven, HalfAwayFromZero, ToZero).
- WHEN
col("w").round(2)is selected over 1.23456 - THEN the result is 1.23
- WHEN
col("w").roundandcol("w").round(mode = HalfAwayFromZero)are selected over 2.5 - THEN the results are 2.0 and 3.0
More aggregations
Expr SHALL support median, var(ddof = 1), std(ddof = 1), quantile(q, interpolation = Nearest) with a pure enum QuantileMethod (Nearest, Lower, Higher, Midpoint, Linear, Equiprobable), and len, which counts rows including nulls.
- WHEN
medianandquantile(0.25, interpolation = Linear)are computed over 1, 2, 3 and 4 - THEN the results are 2.5 and 1.75
- WHEN
lenandcountare computed over 1, null and 3 - THEN the results are 3 and 2
Null fill strategies
Expr SHALL support fillNull(strategy, limit = none(int)) with a pure enum FillNullStrategy (Forward, Backward, Mean, Min, Max, Zero, One), and the shortcuts forwardFill(limit) and backwardFill(limit). limit SHALL also accept a plain int. A limit SHALL bound how many consecutive nulls are filled.
- WHEN
col("a").forwardFill(1)is selected over 1, null, null and 4 - THEN the result is 1, 1, null and 4
- WHEN
col("a").fillNull(Mean)is selected over 1, null and 3 - THEN the result is 1, 2 and 3
Window expressions
Expr SHALL support over(partitionBy) with one column name, a list of names, or a list of expressions. It SHALL compute the expression per group and return one value per row.
- WHEN
col("v").mean.over("g")is selected over groups x, x, y with values 1, 3, 10 - THEN the result is 2, 2 and 10
- WHEN
col("r").forwardFill.over("g")runs where group y starts with a null - THEN that null stays null, instead of taking the last value of group x
Unchanged in this spec: Ranking, Filtering inside expressions, Shape and position aggregations, Boolean aggregations, Entropy, Row count expression, Several window keys and selector concatenation, Null-aware comparisons and closeness, More expression functions
native-bridge modified
Nim declarations mirror the C ABI
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release
Design
Design
Context
Expressions cross the ABI as opaque Expr pointers. Binary operators go through nq_expr_binary(a, NqBinOp, b) and one-argument functions through nq_expr_unary(e, NqUnary). Literals are lifted by lit. Polars 0.55 has:
when(c).then(a)returningThen,.when(c)returningChainedWhen,.thenreturningChainedThen, and.otherwise(e)returningExpr.ThenandChainedThenalso convert intoExpr(otherwise null).is_in(other, nulls_equal)(featureis_in) andis_between(lower, upper, ClosedInterval)(featureis_between).floor_div,%(Rem),pow,abs(featureabs) andround(decimals, RoundMode)(featureround_series).median,var(ddof),std(ddof),quantile(Expr, QuantileMethod)andlen.fill_null_with_strategy(FillNullStrategy)andover(partition_by).
Goals / Non-Goals
Goals:
- One plan, two spellings for conditionals: the chain is the reference, and
chooseis sugar that expands to it. - Strategy and option enums follow the
api-conventionsspec. - Few new ABI functions: extend
NqBinOpandNqUnarywhere the shape fits.
Non-Goals:
- String, temporal and list namespaces.
overwithorder_byor mapping strategies.
Decisions
Conditionals are built in Nim and crossed once
when returns a Nim When value holding the condition. .then(v) returns a Then value holding lists of conditions and values, and .when / .then on it extend those lists. otherwise(e), or the converter to Expr, makes one call:
nq_expr_when_then(conds: *const *const Expr, values: *const *const Expr, n: usize,
otherwise: *const Expr /* NULL: none */) -> *mut Expr
Rust folds the lists into when(c0).then(v0).when(c1).then(v1)... and ends with .otherwise(e), or .otherwise(lit(NULL)) when there is none.
- Why: a single ABI function and no Rust
Then/ChainedThenhandles to free. Nim values are cheap. - Alternative: mirror Rust's four builder types across the ABI. That gives four more opaque types for no gain.
choose macro
choose(body) takes an if statement or expression (nnkIfStmt/nnkIfExpr), and turns each elif branch into .when(cond).then(value) and else into .otherwise(value). Any other node is a compile error with a message that points to if. Values go through lit when they are not Expr. About 30 lines in src/nanuq.nim.
Typed value lifting
then, otherwise and the macro accept Expr or SomeNumber | string | bool, as the binary operators already do. Strings become lit("...").
isIn with Nim values
isIn(values: openArray[T]) builds a Series from the values (the existing series procs), turns it into a literal with nq_expr_lit_series, and calls nq_expr_is_in(e, other, nulls_equal). Rust implodes the literal series when the other side is a plain column, which is what Polars expects in 0.55.
Enums
ClosedInterval, QuantileMethod, FillNullStrategy and RoundMode are pure enums with Rust's names, in Rust's order, mirrored as NqClosedInterval, NqQuantileMethod, NqFillNullStrategy and NqRoundMode (nq_expr_round(e, decimals, mode)). Fill uses nq_expr_fill_null_strategy(e, strategy, has_limit, limit). forwardFill(limit) and backwardFill(limit) are Nim one-liners on top. limit is Option[int], with plain-int overloads (like sample's seed).
Operators
NqBinOp gains Mod (Rust %), FloorDiv and Pow. In Nim, mod, div, ^ and pow are defined with defBinOp, so literals on either side work (2 ^ col("a")). NqUnary gains Abs, Median, Len and Neg.
over
nq_expr_over(e, partition_by, n) with key expressions. Nim overloads take a single name, a list of names, or a list of expressions.
Risks / Trade-offs
- Macro error messages are harder to read than proc errors. The macro checks the node kinds itself and reports "choose expects an if/elif/else expression".
mod/divwith Polars' floor semantics may surprise Nim users who expect truncation. The difference is in the doc comments and the README conventions.
Tasks
1. Bridge
- 1.1Add the Polars features
is_in,is_between,absandround_seriestosrc/rust/Cargo.toml - 1.2Add
NqBinOpvaluesMod,FloorDivandPow, andNqUnaryvaluesAbs,Median,LenandNeg - 1.3Add
nq_expr_when_then,nq_expr_is_in,nq_expr_lit_series,nq_expr_is_between(NqClosedInterval),nq_expr_quantile(NqQuantileMethod),nq_expr_var_std,nq_expr_fill_null_strategy(NqFillNullStrategy),nq_expr_round(NqRoundMode) andnq_expr_over - 1.4Mirror everything in
ffi.nim; verify thatcargo build --releasepasses
2. Nim API
- 2.1Add the conditional chain (
when,then,when,otherwise, and a converter toExpr) and thechoosemacro - 2.2Add
isIn(values and expression) andisBetweenwithClosedInterval - 2.3Add
mod,div,^/pow,abs, unary-, androundwithRoundMode - 2.4Add
median,var,std(ddof),quantilewithQuantileMethod(interpolation), andlen - 2.5Add
fillNull(strategy, limit)withFillNullStrategy, plusforwardFillandbackwardFill - 2.6Add
over(name, names, expressions) - 2.7Write
tests/test_expressions.nim: every function and option, a chain withoutotherwise, string literals in branches, the macro giving the same$expras the chain, a macro misuse failing to compile, floor semantics ofmod/div, and forward fill with and withoutover; add it tonanuq.nimbleand.gitignore
3. Docs and integration
- 3.1List the new expressions in the README, and note in "Conventions" that operators keep Polars' semantics; verify that
nimble testandnimble examplepass - 3.2Check that CI is green on the PR, including the Rust rebuild
Workflow follow-up
Revisions
ab17ee2 Add expression essentials (implements add-expr-essentials)First version: .openspec.yaml, design.md, proposal.md, specs/expressions/spec.md, specs/native-bridge/spec.md, tasks.md
add-expr-filter Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
Two small gaps found while porting real queries to Nanuq during 0.3:
- The performance work on PDS-H found that query 21 needs an extra group-by and join in Nanuq because there is no
Expr.filter, which aggregates over part of a group ("late deliveries per supplier"). That costs about 30% on that query. - The Nanuq Book port found that Python's
pl.col(["a", "b"])(ordf.select(cols)with a list in a variable) has no direct twin:col("a", "b")takes varargs only.
It is the eighth change of the 0.3 release.
What Changes
e.filter(predicate)keeps the values ofewherepredicateis true, for conditional aggregations (agg(col.pts.filter(col.kind == "TT").sum)).col(names)with anopenArray[string]returns aSelectorfor those columns, in order.
Capabilities
Modified Capabilities
expressions:Expr.filter.column-selectors:colwith a list of names.
Differences from Polars
- None in behaviour. Python's
Expr.filteralso takes several predicates and keyword constraints (filter(a, b, kind="TT")); Nanuq takes one expression (combine withand).
Impact
src/rust/src/lib.rs:nq_expr_filter;src/nanuq/ffi.nim,src/nanuq.nim.- Tests in
tests/test_expressions.nimandtests/test_selectors.nim.
Spec changes
column-selectors modified
Selecting by name
Unchanged in this spec: Selecting by Nim type, Excluding columns, Selectors as expressions, Output name suffix and prefix, Operators on selectors
expressions modified
Filtering inside expressions
e.filter(predicate) SHALL keep the values of e where predicate is true, so that an aggregation can run over part of each group.
let df = newDataFrame:
rider: ["Pogačar", "Pogačar", "Vingegaard", "Vingegaard"]
stage: ["TT", "road", "TT", "road"]
secs: [3120, 15400, 3150, 15390]
echo df.groupBy(col.rider).agg(col.secs.filter(col.stage == "TT").sum.alias("tt_secs"))
.sort("rider").collect
TBD
- WHEN
col.secs.filter(col.stage == "TT").sumis aggregated per rider - THEN each rider's sum counts only the TT rows
Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Ranking, Shape and position aggregations, Boolean aggregations, Entropy, Row count expression, Several window keys and selector concatenation, Null-aware comparisons and closeness, More expression functions
Tasks
1. Implementation
- 1.1Add
nq_expr_filterandExpr.filter - 1.2Add
col(openArray[string]) - 1.3Tests;
nimble testandnimble specexamplespass; CHANGELOG
Revisions
c27d0a5 Add Expr.filter and col with a list of namesFirst version: proposal.md, specs/column-selectors/spec.md, specs/expressions/spec.md, tasks.md
add-expr-math Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 4/4
- Archive
Proposal
Why
The Nanuq Book ports stopped on elementwise math more often than on anything else that needs no new data type: the O'Reilly chapter 8 sections on mathematical transformations, trigonometry, rounding and missing or infinite values, and every query that takes a square root or a logarithm. NaN, which Polars keeps apart from null, has no API at all.
It is the first change of the 0.4 release ("A real Series, and shaping", see the Polars coverage map).
What Changes
- Elementwise math on expressions:
sqrt,cbrt,exp,log(base = E),log10,log1p,sign,floor,ceil,clip(lowerBound, upperBound)(or one bound, named), anddot(other). - Trigonometry:
sin,cos,tan,cot,arcsin,arccos,arctan,sinh,cosh,tanh,arcsinh,arccosh,arctanh,degrees,radians, andarctan2(y, x). - NaN and infinity:
isNan,isNotNan,isFinite,isInfinite,fillNan(value),dropNans, andExpr.dropNulls. - The wrapper crate becomes
0.4.0-devand gains the Polars features 0.4 needs.
Capabilities
New Capabilities
math-functions: elementwise math, trigonometry, NaN and infinity.
Differences from Polars
clipwith one bound needs the bound named (clip(lowerBound = 0)): a single positional argument is a compile error, because Nim can't tell which bound it is. Python takesclip(lower_bound=None, upper_bound=None); Rust hasclip,clip_minandclip_max.log(base)defaults to e as in Python (Rust always takes the base). Nim's std/mathln,log2are not added;log(2.0)does that.arctan2(y, x)is a free function as in Python (pl.arctan2); in Rust it is a method.- These names overload std/math's float procs (
sqrt,exp,floor, ...) forExpr; both work in the same module.
Impact
src/rust/Cargo.toml(version, features),src/rust/src/lib.rs(NqUnarygrows,nq_expr_clip,nq_expr_log,nq_expr_binary_fn),src/nanuq/ffi.nim,src/nanuq.nim.- New
tests/test_math.nim.
Spec changes
math-functions modified
Elementwise math
Expressions SHALL have sqrt, cbrt, exp, log(base = E), log10, log1p, sign, floor and ceil, computed value by value as in Polars, with nulls staying null. sqrt, cbrt, exp and the logarithms SHALL return Float64 for integer input.
let df = newDataFrame:
x: [1.0, 4.0, 10.0, nil]
echo df.select(col.x.sqrt.alias("sqrt"), col.x.log10.alias("log10"),
col.x.log(2.0).alias("log2"), col.x.exp.round(1).alias("exp"))
TBD
- WHEN
sqrtruns on an Int64 column holding 4 and 9 - THEN the result is a Float64 column holding 2.0 and 3.0
- WHEN
sign,floorandceilrun on -2.5 and 1.5 - THEN they give -1 and 1, -3.0 and 1.0, -2.0 and 2.0
Clipping
clip(lowerBound, upperBound) SHALL limit values to the range, and clip(lowerBound = v) or clip(upperBound = v) SHALL limit them on one side. Bounds SHALL be literals or expressions.
let df = newDataFrame:
anomaly: [-2.1, -0.3, 0.4, 2.6]
echo df.select(col.anomaly.clip(-1.0, 1.0).alias("both"),
col.anomaly.clip(lowerBound = 0.0).alias("warm_only"))
TBD
- WHEN
clip(-1.0, 1.0)runs on -2.1 and 2.6 - THEN the result is -1.0 and 1.0
Trigonometry
Expressions SHALL have sin, cos, tan, cot, arcsin, arccos, arctan, sinh, cosh, tanh, arcsinh, arccosh, arctanh, degrees and radians, working in radians, and arctan2(y, x) SHALL return the angle of the point (x, y).
let df = newDataFrame:
deg: [0.0, 90.0, 180.0]
echo df.select(col.deg.radians.sin.round(3).alias("sin"),
arctan2(lit(1.0), lit(1.0)).degrees.alias("atan2"))
TBD
- WHEN
radiansand thendegreesrun on 90.0 - THEN the result is 90.0
NaN and infinity
isNan, isNotNan, isFinite and isInfinite SHALL test float values (nulls give null), fillNan(value) SHALL replace NaN with a literal or expression, dropNans SHALL remove NaN values and Expr.dropNulls SHALL remove nulls. NaN SHALL stay distinct from null, as in Polars.
let df = newDataFrame:
x: [1.0, NaN, Inf, nil]
echo df.select(col.x.isNan.alias("nan"), col.x.isFinite.alias("finite"),
col.x.fillNan(0.0).alias("filled"))
echo df.select(col.x.dropNans.dropNulls)
TBD
- WHEN
isNullruns on a column holding NaN - THEN the result is false
- WHEN
fillNan(0.0)runs on NaN and null - THEN the result is 0.0 and null
Dot product
a.dot(b) SHALL return the sum of the elementwise products of two columns, as an aggregation.
let df = newDataFrame:
a: [1, 2, 3]
b: [4, 5, 6]
echo df.select(col.a.dot(col.b))
TBD
- WHEN
col.a.dot(col.b)runs on a = 1, 2, 3 and b = 4, 5, 6 - THEN the result is one row holding 32
Tasks
1. Implementation
- 1.1Crate version 0.4.0-dev and the Polars features for 0.4
- 1.2Unary math, trigonometry and NaN functions through
NqUnary - 1.3
log,clip,fillNan,dot,arctan2 - 1.4Tests in
tests/test_math.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
570d956 Nanuq 0.4, changes 1-7: math, cumulative, rolling, value functions, horizontal, reshaping, time groupingFirst version: proposal.md, specs/math-functions/spec.md, tasks.md
add-expression-plugins Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 7/7
- Archive
Proposal
Why
Polars can be extended with expression plugins: shared libraries that Polars loads and calls on Arrow arrays (Python's register_plugin_function). They are how polars-stats (vectorized distributions) and similar extensions ship. The plugin boundary is a plain C ABI (polars-ffi version_0, ABI 0.1), so a plugin can be written in Rust with pyo3-polars, or in Nim.
The exploration "Polars plugins, without the Rust" (nanuq-more, 2026-11-05) wrote two plugins in Nim (ISO weeks as an extension type, and probability distributions) and loaded the same library from Python Polars and from Nanuq. Nanuq needed one new function for that, which this change proposes. Not from a BACKLOG.md entry.
What Changes
registerPluginFunction(pluginPath, functionName, args, kwargs, isElementwise, changesLength, returnsScalar, castToSupertype, inputWildcardExpansion, passNameToApply, isDeterministic): Expr, as in Python Polars.kwargsare bytes already pickled (a dict), as Polars passes them to the plugin.- The C bridge gets
nq_expr_plugin, which buildsFunctionExpr::FfiPlugin. The crate enables the Polars featuresffi_plugin(polars-plan and polars-lazy) anddtype-extension, so a plugin can return an extension type (ext[...]). tests/test_plugins.nimbuilds a minimal Nim plugin (tests/data/plugins/double_it.nim, the ABI by hand) and checks a call, an error and a lazy group-by.
Capabilities
New Capabilities
expression-plugins: calling Polars expression plugins from Nanuq.
Differences from Polars
- Python resolves a relative
plugin_pathagainst the virtual environment and also accepts a directory; Nanuq takes the library file, relative to the working directory (made absolute), and has nouse_abs_path. - Python pickles a
kwargsdict itself; Nanuq takes the pickled bytes (nanuq-more has a small pickle writer). A typed kwargs parameter could come later. - Rust Polars builds the same expression through
Expr::FunctionwithFunctionExpr::FfiPlugin; it has no public helper of this name. - Extension types show as
ext[<name>](Python shows the registered class's repr); Nanuq has no registry of extension classes.
Impact
src/rust/Cargo.toml(features),src/rust/src/lib.rs,src/nanuq/ffi.nim,src/nanuq.nim, a new test and its fixture. Needs a new library release.- Rust plugins built with pyo3 (polars-stats) link against libpython: Nanuq can load them only with libpython preloaded (
LD_PRELOAD). Plugins written in Nim (or plain Rust without pyo3) load directly. - The plugin ABI is Polars' version 0 and extension types are unstable in Polars: either may change in a Polars release.
Spec changes
expression-plugins modified
Calling an expression plugin
registerPluginFunction(pluginPath, functionName, args) SHALL give an expression that calls the function functionName of the Polars expression plugin at pluginPath (a shared library implementing the Polars plugin ABI 0.1) on the columns of args, with the options of Python's register_plugin_function (kwargs as pickled bytes, isElementwise, changesLength, returnsScalar, castToSupertype, inputWildcardExpansion, passNameToApply, isDeterministic). The output name and data type SHALL be the ones the plugin reports, extension types included. The expression SHALL compose like any other, lazily and in group-bys.
# tests/data/plugins/double_it.nim, built as a library
let lib = "tests/data/plugins/" & (DynlibFormat % "double_it")
let df = newDataFrame(series("x", [1.5, 2.0, 4.0]))
echo df.select(registerPluginFunction(lib, "double_it", [col"x"], isElementwise = true))
shape: (3, 1)
┌─────┐
│ x │
│ --- │
│ f64 │
╞═════╡
│ 3.0 │
│ 4.0 │
│ 8.0 │
└─────┘
- WHEN the plugin reports an error for a call (it returns no column and sets its last error message)
- THEN running the query raises
ComputeErrorwith the plugin's message
- WHEN
pluginPathis not a loadable library - THEN running the query raises
ComputeErrornaming the path
- WHEN the plugin's output field carries
ARROW:extension:name - THEN the column has that extension type, shown as
ext[<name>]
Tasks
1. Bridge
- 1.1
nq_expr_pluginin src/rust/src/lib.rs; Polars featuresffi_pluginanddtype-extension - 1.2
nq_expr_pluginin src/nanuq/ffi.nim
2. API
- 2.1
registerPluginFunctionin src/nanuq.nim - 2.2tests/test_plugins.nim with the double_it fixture plugin
- 2.3Spec delta for
expression-plugins, with an example - 2.4Before archiving: the spec suite builds tests/data/plugins/double_it.nim so the example runs
- 2.5README and coverage map (
register_plugin_function)
Revisions
60f21f8 Release 0.6.1: archive add-expression-plugins, bump to 0.6.1First version: proposal.md, specs/expression-plugins/spec.md, tasks.md
add-frame-utilities Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
The 0.4 book ports left a list of smaller Polars functions (BACKLOG.md, "Smaller Polars functions found by the 0.4 book ports"), and the 0.5 tally of "not yet" book sections adds a few more: equals (7 sections), upsample (6), vstack/hstack/extend, estimated_size, collect_all, update, meta.* and name.to_lowercase. Each is small.
It is the eighth change of the 0.5 release. It takes up that BACKLOG.md entry.
What Changes
- Expressions:
over(partitionBy, mappingStrategy),shuffle,sample,hash,get,argTrue,upperBound,lowerBound,extendConstant,rle,reshape;name.toLowercase,name.toUppercase;e.metawithoutputName,rootNames,hasMultipleOutputs,isColumn,isLiteral,undoAliases. - Frames:
equals(also on Series),vstack,hstack,extend,update,upsample,estimatedSize,partitionBy(asDict = true), andcollectAllfor several LazyFrames.
Capabilities
New Capabilities
frame-utilities: the smaller expression and frame functions above.
Differences from Polars
MappingStrategyis a pure enum (GroupToRows,Join,Explode), not a string.partitionBy(asDict = true)keys its table by the key values as strings (@["Biscoe"]), since Nim has no tuples of run-time types; Python keys by tuples of values.hash(seed)uses one seed for Polars' four (seed,seed_1,seed_2,seed_3in Python default to it too).estimatedSizegives bytes as an int;estimatedSize(unit)a float inSizeUnit.updatesupportshow = Left,InnerandFullwithoncolumns (or the row index), as Python does;includeNullsis left out.extendreturns a new frame (Nanuq frames are immutable), so it isvstack.
Impact
src/rust/src/lib.rsandsrc/nanuq/ffi.nim:nq_expr_util,nq_expr_reshape,nq_expr_over_mapping,nq_expr_meta_*,nq_df_equals,nq_df_estimated_size,nq_df_upsample,nq_collect_all.src/nanuq.nim; BACKLOG.md entry removed.- New
tests/test_utilities.nim.
Spec changes
frame-utilities modified
Smaller expression functions
Expressions SHALL have shuffle(seed), sample(n or fraction), hash(seed), get(i), argTrue, upperBound, lowerBound, extendConstant(value, n), rle (a struct of len and value) and reshape(dims), and over(partitionBy, mappingStrategy) with MappingStrategy.GroupToRows, Join or Explode.
let df = newDataFrame:
den: ["A", "A", "B"]
kg: [410, 380, 500]
echo df.select(col("kg").get(1).alias("second"), col("kg").upperBound.alias("max"))
echo df.select((col("kg") > 400).argTrue.alias("heavy"))
echo df.select(col("den"), col("kg").over("den", MappingStrategy.Join).alias("all"))
echo df.select(col("den").rle).unnest("den")
TBD
- WHEN
shuffle(seed = 1)is evaluated twice - THEN both results are the same permutation
Names and meta
name.toLowercase and name.toUppercase SHALL change output names, and e.meta SHALL give outputName, rootNames, hasMultipleOutputs, isColumn, isLiteral and undoAliases.
let e = (col("kg") * 2).alias("double")
echo e.meta.outputName, " ", e.meta.rootNames, " ", col("*").meta.hasMultipleOutputs
let df = newDataFrame:
Bear: ["Ada"]
echo df.select(col("Bear").name.toUppercase).columns
TBD
- WHEN
outputNameis asked ofcol("*") - THEN
ComputeErroris raised
Comparing and stacking frames
a.equals(b, nullEqual = true) SHALL tell whether two frames (or Series) have the same names, types and values; vstack and extend SHALL append the rows of a frame with the same schema, and hstack SHALL add Series or the columns of another frame.
let a = newDataFrame:
bear: ["Ada"]
kg: [410]
let b = newDataFrame:
bear: ["Bo"]
kg: [380]
echo a.vstack(b).hstack([series("den", ["A", "B"])])
echo a.equals(a), " ", a.equals(b)
TBD
- WHEN two frames with a null in the same place are compared with
nullEqual = false - THEN
equalsis false
Updating, upsampling and partitions
df.update(other, on, how) SHALL replace values of df with the non-null values of other in matching rows; df.upsample(timeColumn, every, groupBy) SHALL insert rows for missing times at a regular interval; estimatedSize SHALL give the frame's size; partitionBy(by, asDict = true) SHALL give a table from key values to frames; and collectAll(lfs) SHALL collect several LazyFrames.
let df = newDataFrame:
bear: ["Ada", "Bo"]
kg: [410, 380]
let fix = newDataFrame:
bear: ["Bo"]
kg: [395]
echo df.update(fix, on = "bear")
let t = newDataFrame:
day: [date(2026, 3, 1), date(2026, 3, 4)]
seen: [3, 1]
echo t.upsample("day", every = "1d")
echo df.partitionBy("bear", asDict = true).len, " ", collectAll([df.lazy, fix.lazy]).len
TBD
- WHEN
upsampleis called withgroupBy - THEN each group is filled between its own first and last time
Unchanged in this spec: Operator methods and xor, Ranges per row, Inequality joins, Frame and Series helpers, Unstack, Rolling Nim functions, Data type of an expression, Empty frames, Frame shortcuts, Schema matching, Merging sorted frames, Query optimizations
Tasks
1. Implementation
- 1.1Crate: utility ops, reshape, over with mapping, meta, equals, estimated size, upsample, collect_all
- 1.2Nim API for expressions and frames
- 1.3Tests in
tests/test_utilities.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
f94c8b7 0.5: Nim callbacks and smaller functions (add-nim-callbacks, add-frame-utilities)First version: proposal.md, specs/frame-utilities/spec.md, tasks.md
add-frame-utilities-0-6 Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
After 0.5 the book map (planning/book-ports-0.6.md) still finds sections blocked by single functions: append 5, unstack 3, ranges 3, method spellings (mul, sub) 4, dtype_of 4, join_where, rolling_map, explain_all, is_sorted, from_epoch, read_parquet_schema, hist, scatter/set, remove. Each is small; together they unblock about 25 sections.
It is the ninth change of the 0.6 release.
What Changes
- Method spellings of operators:
add,sub,mul,truediv,floordiv,eq,ne,lt,le,gt,ge,neg;xor(logical on booleans, bitwise on integers). intRanges,dateRanges,datetimeRanges(one list per row),arange(intRange).joinWhere(other, predicates...)(inequality joins),explainAll(lfs).histon Expr and Series;setSortedon Expr and DataFrame;Series.isSorted.append(frame, in place),remove(predicate)(the opposite offilter).fromEpoch(column, EpochUnit),readParquetSchema(path),threadPoolSize().unstack(step, how, columns, fillValues).rollingMap(f, windowSize, minPeriods, center)with a typed Nim proc of a window.Series.scatter(indices, values)andSeries.set(mask, value).dtypeOf(expr | column)withcast(e, dtypeOf(...)),displayandinnerDtype.
Capabilities
Modified Capabilities
frame-utilities: the functions above.
Differences from Polars
- Python's
and_/or_methods have no Nim spelling (a trailing underscore is not a Nim identifier);a.and(b)anda.or(b)already work as operator calls (a.and(b)). rollingMappasses the window's non-null values as aseq[T]to a typed proc (Python passes a Series to a Python function) and runs on the whole column at once, withoutweights.unstacktakes afillValuesexpression (Python also takes a list per column).fromEpochtakes anEpochUnitenum (Python strings"d","s","ms","us","ns").dtypeOfsupportscast,displayandinnerDtype; the rest of Python's datatype expressions (matches,to_dtype, struct and integer helpers) is left out.setis spelledsetwhen called with a prefix (s.set(mask, 0)), assetis also Nim's set type.histon a Series includesbreakpointandcategoryby default, as Python does; on an Expr it does not.
Impact
src/rust/src/lib.rs,src/nanuq/ffi.nim:nq_expr_xor,nq_expr_set_sorted,nq_expr_hist,nq_expr_int_ranges,nq_expr_date_ranges,nq_lf_join_where,nq_explain_all,nq_thread_pool_size,nq_expr_cast_dtype_of,nq_expr_dtype_display.src/nanuq.nim: the procs above (several in Nim on top of existing API).- New
tests/test_utilities6.nim.
Spec changes
frame-utilities modified
Operator methods and xor
Expressions SHALL have the method spellings add, sub, mul, truediv, floordiv, eq, ne, lt, le, gt, ge (with an expression, number, string or bool) and neg, giving the same result as the operators, and xor SHALL be logical on booleans and bitwise on integers.
let df = newDataFrame(series("a", @[6, 3]), series("ok", @[true, false]))
echo df.select(col("a").mul(2).alias("m"), col("a").floordiv(4).alias("f"),
(col("a") xor 5).alias("x"), (col("ok") xor true).alias("nx"))
TBD
- WHEN
col("a").sub(1)andcol("a") - 1are selected - THEN both columns are equal
Ranges per row
intRanges(start, stop, step = 1, dtype = Int64), dateRanges(start, stop, interval) and datetimeRanges(start, stop, interval, closed, timeUnit, timeZone) SHALL give one list per row, with columns or values as bounds; arange SHALL be intRange.
let df = newDataFrame(series("lo", @[1, 3]), series("hi", @[3, 6]))
echo df.select(intRanges(col("lo"), col("hi")).alias("r"))
TBD
- WHEN
dateRangesruns from 2024-01-01 to 2024-01-03 - THEN the list holds 3 dates
Inequality joins
joinWhere(other, predicates..., suffix = "_right") on DataFrames and LazyFrames SHALL join the rows of both frames for which every predicate holds; clashing columns of other SHALL get suffix.
let east = newDataFrame(series("id", @[100, 101]), series("dur", @[140, 100]))
let west = newDataFrame(series("t_id", @[404, 498]), series("time", @[90, 130]))
echo east.joinWhere(west, col("dur") < col("time"))
TBD
- WHEN no pair of rows satisfies the predicates
- THEN the result has no rows
Frame and Series helpers
The API SHALL provide append (rows of another frame, in place), remove(predicate) (rows where it is not true), setSorted, Series.isSorted(descending, nullsLast), explainAll(lfs), threadPoolSize(), readParquetSchema(path), fromEpoch(column, unit), hist(bins, binCount, includeCategory, includeBreakpoint) on Expr and Series, Series.scatter(indices, values) and set(mask, value) .
var df = newDataFrame(series("a", @[1, 2]))
df.append(newDataFrame(series("a", @[3])))
echo df.remove(col("a") == 2)
echo series("x", @[1.0, 2.0, 2.5, 4.0]).hist(bins = [0.0, 2.0, 4.0])
echo series("x", @[1, 2, 3]).scatter([0, 2], [10, 30])
TBD
- WHEN
remove(col("a") > 1)runs on a column with a null - THEN the null row stays
Unstack
unstack(step, how = UnstackDirection.Vertical, columns = [], fillValues = nil) SHALL reshape each column into columns <name>_<i> of step values each (Vertical) or with step values per row (Horizontal), padding the end with nulls or fillValues.
let df = newDataFrame(series("x", @["a", "b", "c", "d", "e"]))
echo df.unstack(2)
TBD
- WHEN 5 values are unstacked horizontally with step 2 and fill 0
- THEN column
_0holds values 1, 3, 5 and column_1holds 2, 4, 0
Rolling Nim functions
rollingMap(f, windowSize, minPeriods = windowSize, center = false) SHALL apply a typed Nim proc to each window's non-null values, giving null when a window has fewer than minPeriods values.
import std/sequtils
let df = newDataFrame(series("x", @[1.0, 2.0, 3.0, 4.0]))
echo df.select(col("x").rollingMap(proc (w: seq[float]): float = w.foldl(a + b), windowSize = 2))
TBD
- WHEN
center = truewith window 3 - THEN each value's window is the value and its two neighbours
Data type of an expression
dtypeOf(expr or column) SHALL stand for the type of an expression at run time: cast(e, dtypeOf(...)) casts to it, display gives its short name as a string value, innerDtype the inner type of a List or Array.
let df = newDataFrame(series("a", @[1.5, 2.5]), series("b", @[1'i32, 2'i32]))
echo df.select(col("a").cast(dtypeOf("b"), strict = false), dtypeOf("b").display.alias("type"))
TBD
- WHEN
dtypeOf("nope")is used - THEN
ColumnNotFoundErroris raised when the query runs
Unchanged in this spec: Smaller expression functions, Names and meta, Comparing and stacking frames, Updating, upsampling and partitions, Empty frames, Frame shortcuts, Schema matching, Merging sorted frames, Query optimizations
Tasks
1. Implementation
- 1.1Crate: xor, setSorted, hist, intRanges, dateRanges/datetimeRanges, joinWhere, explainAll, threadPoolSize, dtypeOf
- 1.2Nim: the API, including Nim-only helpers (append, remove, isSorted, fromEpoch, readParquetSchema, unstack, rollingMap, scatter, set)
- 1.3Tests in
tests/test_utilities6.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
4ea5dad 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6First version: proposal.md, specs/frame-utilities/spec.md, tasks.md
add-frame-verbs Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 13/13
- Archive
Proposal
Why
Nanuq can filter, select and sort by one column. But a lot of everyday table work happens between those steps: dropping or renaming columns, looking at the last rows or a window of them, taking a random sample, removing duplicate rows, numbering rows, and sorting by several keys with nulls at the end. Polars has a small, stable verb for each of these. Without them, Nanuq users have to write select lists by hand or go back through Nim seqs.
This is the third change of the 0.2 release (see the Polars coverage map, area "Frame verbs"). It has no BACKLOG.md entry.
What Changes
- New verbs on LazyFrame, with eager DataFrame shortcuts:
drop("a")ordrop(["a", "b"], strict = true)removes columns.rename({"old": "new"}, strict = true)renames columns.head(n = 5)(LazyFrame; DataFrame already has it) andtail(n = 5)keep the first or last rows.slice(offset)andslice(offset, length)keep a window of rows. A negative offset counts from the end.unique("a", keep = First, maintainOrder = false)(or a list of names) drops duplicate rows, judged on all columns or on the named ones.keepis aUniqueKeepStrategy:Any(default),First,LastorNone.reverse()reverses the row order.withRowIndex(name = "index", offset = 0)adds a row number column first.- Sorting by several keys:
sort(["species", "mass"], descending = [false, true], nullsLast = [true], maintainOrder = false), by column names or expressions. A single value indescendingornullsLastapplies to every key. The one-columnsort(by, descending)gainsnullsLastandmaintainOrder. sampleon DataFrame:sample(n, withReplacement = false, shuffle = false, seed = none(int)), andsample(fraction = 0.1, ...).seed = 42works too, andsetRandomSeed(42)seeds Polars' global generator (added during implementation, after Pietro picked this option for the 0.2 explainer).- New pure enum
UniqueKeepStrategy, following theapi-conventionsspec. - Polars feature
randomis compiled in (forsample). The ABI stays0.2.0-dev.
Capabilities
New Capabilities
frame-verbs: column and row verbs on DataFrames and LazyFrames (drop, rename, head/tail/slice, unique, reverse, withRowIndex, sample) and sorting by several keys.
Modified Capabilities
native-bridge:NqUniqueKeepStrategyjoins the enums that keep the same order in Rust andffi.nim.
Differences from Polars
Expected differences from Polars' Rust and Python APIs:
keepis an enum. Python'skeep="first"becomeskeep = First(pure enumUniqueKeepStrategy, Rust's type and names).descendingandnullsLastin multi-key sort are lists. Python takes a bool or a list. Nim takesopenArray[bool]: one value applies to all keys, as in Rust'sSortMultipleOptions. Empty (the default) means all false. The one-columnsortkeeps plain bools.slicewithout a length is a separate overload instead of Python'slength=None.sampleis DataFrame only, as in Python (LazyFrame has nosample).nandfractionare two overloads, chosen by the argument name (fraction = 0.1) or type, and one of them is required (Python defaults to one row when both are missing).seedis anOption[int]or a plainint.setRandomSeedis Python'spl.set_random_seed.renametakes pairs only. Python also accepts a function from old to new name. That form is left for later.droptakes one name or a list, not Python's*columns: Nimvarargsfollowed bystrictcan't take several positional names, sodrop("a", "b")is writtendrop(["a", "b"]).unique's subset is one name or a list, as in Python. Selectors and expressions come with the column selectors change.- Not in this change:
dropwith selectors,gather_every,shift,top_k/bottom_k,clear,first/laston frames,with_row_count(deprecated in Python), and sort'smultithreadedflag. They stay in the coverage map. - Names follow Polars in camelCase:
with_row_index→withRowIndex,nulls_last→nullsLast,maintain_order→maintainOrder,with_replacement→withReplacement.
Impact
src/rust/src/lib.rs:nq_lf_drop,nq_lf_rename,nq_lf_slice,nq_lf_unique,nq_lf_reverse,nq_lf_with_row_index,nq_df_sample, andnq_lf_sort_byreplacingnq_lf_sort. New#[repr(C)]enumNqUniqueKeepStrategy.Cargo.tomladds therandomfeature. CI rebuilds the Rust library.src/nanuq/ffi.nimandsrc/nanuq.nimget the matching declarations, the enum and the procs.tests/test_verbs.nimcovers each verb and its options.README.mdlists the new verbs in "What is there".
Spec changes
frame-verbs modified
Dropping and renaming columns
LazyFrame and DataFrame SHALL support drop(columns, strict = true), with one column name or a list of names, and rename(mapping: openArray[(string, string)], strict = true). With strict = true, a column that does not exist SHALL raise NanuqError. With strict = false, it SHALL be ignored.
- WHEN
df.drop("b")runs on columnsa,b,c - THEN the columns are
a,c, anddf.drop(["a", "b"])leavesc
- WHEN
df.rename({"a": "x"})runs on columnsa,b - THEN the columns are
x,b
- WHEN
df.drop("zzz")runs - THEN
NanuqErroris raised, anddf.drop("zzz", strict = false)returns the frame unchanged
Row windows
LazyFrame and DataFrame SHALL support head(n = 5), tail(n = 5), slice(offset) and slice(offset, length). A negative offset SHALL count from the end. reverse() SHALL reverse the row order.
- WHEN
tail(2)runs on rows 1 to 5 - THEN the result is rows 4 and 5
- WHEN
slice(-3, 2)runs on rows 1 to 5 - THEN the result is rows 3 and 4
- WHEN
slice(1)runs on rows 1 to 5 - THEN the result is rows 2 to 5
Unique rows
LazyFrame and DataFrame SHALL support unique(subset = [], keep, maintainOrder = false), with one column name or a list of names, judging duplicates on all columns when the subset is empty. keep is a pure enum UniqueKeepStrategy (Any (default), First, Last, None). With maintainOrder = true, the rows SHALL keep their original order.
- WHEN
unique("k", keep = First, maintainOrder = true)runs on keys a, b, a with values 1, 2, 3 - THEN the result is (a, 1), (b, 2)
- WHEN the same frame is made unique on
kwithkeep = None - THEN only (b, 2) remains
Row index
LazyFrame and DataFrame SHALL support withRowIndex(name = "index", offset = 0), which adds an unsigned integer column with that name as the first column, counting from offset.
- WHEN
withRowIndex("n", offset = 1)runs on three rows - THEN the first column is
nwith values 1, 2, 3
Sorting by several keys
LazyFrame and DataFrame SHALL sort by several column names or expressions with sort(by, descending: openArray[bool] = [], nullsLast: openArray[bool] = [], maintainOrder = false). An empty list SHALL mean false for every key, and one value SHALL apply to every key. Another length SHALL raise NanuqError. The one-column sort(by: string, descending = false, nullsLast = false, maintainOrder = false) SHALL remain.
- WHEN a frame is sorted by
["g", "v"]withdescending = [false, true] - THEN rows are ordered by
gascending and, within eachg, byvdescending
- WHEN a column holding null, 2, 1 is sorted with
nullsLast = true - THEN the order is 1, 2, null
- WHEN a sort by three keys gets
descending = [true, false] - THEN
NanuqErroris raised
Sampling rows
DataFrame SHALL support sample(n, withReplacement = false, shuffle = false, seed = none(int)) and sample(fraction, ...) with the same options. Asking for more rows than there are without replacement SHALL raise NanuqError. The same seed SHALL give the same rows.
- WHEN
sample(3, seed = some(42))runs twice on the same 10-row frame - THEN both results have 3 rows and are equal
- WHEN
sample(fraction = 0.5)runs on 10 rows - THEN the result has 5 rows
- WHEN
sample(11)runs on 10 rows - THEN
NanuqErroris raised
Unchanged in this spec: Every n-th row, Frame interpolation, Casting by data type, Several filter predicates, Group order parameter, Frame aggregations, Group-by shortcuts, Iterating over groups, Frame fillNan and select without a frame
native-bridge modified
Nim declarations mirror the C ABI
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release
Design
Design
Context
Lazy verbs cross the ABI as functions that borrow a LazyFrame and return a new one. Lists of names go across as a pointer and a length. Enums cross as #[repr(C)] integers mirrored in ffi.nim. DataFrame verbs are eager shortcuts: df.lazy.<verb>.collect.
Polars 0.55 has:
LazyFrame::drop(Selector),rename(existing, new, strict),slice(offset: i64, len: IdxSize),tail(n)andlimit(n).unique_generic(Option<Vec<Expr>>, UniqueKeepStrategy)and itsunique_stablevariant,reverse(),with_row_index(name, Option<IdxSize>), andsort_by_exprs(exprs, SortMultipleOptions).DataFrame::sample_n_literalandsample_frac, behind therandomfeature.
Goals / Non-Goals
Goals:
- Each verb Python Polars has on DataFrame and LazyFrame in this list, with the same defaults.
- One Rust function per verb, carrying all of its options.
Non-Goals:
- Selectors (
cs.numeric(), regex) as verb arguments. That is the column selectors change, which can widendropanduniquelater without breaking these forms. - A lazy
sample. Python has none. It would need a select over every column withsample_n.
Decisions
drop and strict
nq_lf_drop(lf, names, n, strict) builds by_name(names, strict). With strict = true, a missing column raises NanuqError when the query runs, as in Python.
rename keeps both lists
nq_lf_rename(lf, existing, new, n, strict) maps onto LazyFrame::rename. Nim takes openArray[(string, string)], so df.rename({"a": "x"}) reads like cast({"a": Int32}).
slice, head, tail
nq_lf_slice(lf, offset: i64, len: u32). When there is no length, Nim passes high(uint32), as Python does for length=None. LazyFrame head(n) is limit(n). tail(n) is slice(-n, n), done in Nim with no extra ABI function.
unique
nq_lf_unique(lf, names, n, keep: NqUniqueKeepStrategy, maintain_order) calls unique_stable_generic when maintain_order, and unique_generic otherwise. An empty subset means all columns.
One sort function
nq_lf_sort_by(lf, exprs, n, descending: *const bool, n_desc, nulls_last: *const bool, n_nulls, maintain_order) replaces nq_lf_sort. Nim builds col(name) for string keys. Rust passes the bool lists to SortMultipleOptions as they are: an empty list becomes [false], and one value broadcasts. A list whose length is neither 1 nor the number of keys raises NanuqError.
- Why: one ABI function covers single and multiple keys and both key forms. The one-column
sort(by: string, ...)in Nim becomes a thin wrapper.
sample on DataFrame
nq_df_sample(df, n: usize, fraction: f64, by_fraction: bool, with_replacement, shuffle, has_seed, seed: u64). Nim overloads sample(df, n: int, ...) and sample(df, fraction: float, ...). seed = none(int) means a random seed. A negative seed raises ValueError in Nim before the call.
- Alternative:
n = -1andfraction = NaNas "unset" in one proc. Overloads read better and give a compile error when neither is passed.
withRowIndex
nq_lf_with_row_index(lf, name, offset: u32). A negative offset raises ValueError in Nim.
Risks / Trade-offs
- The
randomfeature adds therandcrates to the build. That costs seconds against the Polars build. - Replacing
nq_lf_sortchanges the ABI. That is fine within0.2.0-dev.
Tasks
1. Bridge
- 1.1Add the Polars feature
randomtosrc/rust/Cargo.toml - 1.2Add
nq_lf_drop,nq_lf_rename,nq_lf_slice,nq_lf_reverseandnq_lf_with_row_index - 1.3Add
NqUniqueKeepStrategyandnq_lf_unique(stable whenmaintain_order) - 1.4Replace
nq_lf_sortwithnq_lf_sort_by(expressions, bool lists,maintain_order) - 1.5Add
nq_df_sample(n or fraction, replacement, shuffle, optional seed) - 1.6Mirror everything in
ffi.nim; verify thatcargo build --releasepasses
2. Nim API
- 2.1Add
drop,rename,head(LazyFrame),tail,slice,reverseandwithRowIndexon LazyFrame, with DataFrame shortcuts - 2.2Add the pure enum
UniqueKeepStrategyandunique - 2.3Add multi-key
sort(names and expressions), andnullsLastandmaintainOrderon the one-columnsort - 2.4Add
sampleon DataFrame (n and fraction overloads) - 2.5Write
tests/test_verbs.nimcovering each verb, strict failures, negative offsets, every keep strategy, sort broadcasting and the length mismatch error, and seeded samples that repeat; add it tonanuq.nimbleand.gitignore
3. Docs and integration
- 3.1List the new verbs in the README "What is there"; verify that
nimble testandnimble examplepass - 3.2Check that CI is green on the PR, including the Rust rebuild
Workflow follow-up
Revisions
32f6987 Add frame verbs (implements add-frame-verbs)First version: .openspec.yaml, design.md, proposal.md, specs/frame-verbs/spec.md, specs/native-bridge/spec.md, tasks.md
e3c1120 Add setRandomSeed and plain int seed for sampleproposal.mdadd-horizontal-and-ranges Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 4/4
- Archive
Proposal
Why
Wide tables keep one measurement per column (monthly rainfall in twelve columns, a score per judge), and the natural questions run across a row: the total, the warmest month, whether any value is missing, the first value that is present. Polars answers them with horizontal functions, which Nanuq lacks: the O'Reilly chapter 9 sections "Using functions" and "When, then, otherwise" stop on sum_horizontal, all_horizontal and any_horizontal. Generated columns (int_range, repeat, linear_space) and correlation (pl.corr, which the 0.4 explainer needs to relate El Niño to world temperature) are missing too.
It is the fifth change of the 0.4 release.
What Changes
- Horizontal functions:
sumHorizontal,meanHorizontal(both withignoreNulls),minHorizontal,maxHorizontal,allHorizontal,anyHorizontalandcoalesce, taking expressions, literals, selectors or a list of column names. - Ranges:
intRange(start, stop, step, dtype),linearSpace(start, stop, numSamples, closed),repeat(value, n). - Correlation:
corr(a, b, correlationMethod, propagateNans)with aCorrelationMethodpure enum (Pearson,Spearman), andcov(a, b, ddof).
Capabilities
New Capabilities
horizontal-functions: horizontal functions, ranges, correlation.
Differences from Polars
corr's method parameter is calledcorrelationMethodbecausemethodis a Nim keyword (Python:method="pearson"); usually it is passed positionally:corr("a", "b", Spearman).sumHorizontalandmeanHorizontaltakeignoreNullsonly in the overloads with a list (sumHorizontal([col.a, col.b], ignoreNulls = false)), because the main overload takes any number of arguments.repeatof a string needslit(repeat(lit("x"), 3)): with a plain string, std/strutils'repeatis chosen.intRangewith one argument counts from 0, as Python'spl.int_range(n).- Not included:
fold,reduce,cum_fold(need Nim callbacks, 0.5),concat_list(List columns, 0.5),cum_sum_horizontal(returns a Struct),int_ranges.
Impact
src/rust/src/lib.rs:nq_expr_horizontal,nq_expr_int_range,nq_expr_linear_space,nq_expr_repeat,nq_expr_corr;src/nanuq/ffi.nim,src/nanuq.nim.- New
tests/test_horizontal.nim.
Spec changes
horizontal-functions modified
Horizontal functions
sumHorizontal, meanHorizontal, minHorizontal, maxHorizontal, allHorizontal, anyHorizontal and coalesce SHALL compute row by row over their arguments, which SHALL be expressions, literals, selectors (expanded to their columns) or a list of column names. sumHorizontal and meanHorizontal SHALL skip nulls unless ignoreNulls = false, and coalesce SHALL return the first non-null value.
let df = newDataFrame:
station: ["Lima", "Piura", "Tumbes"]
jan: [1.0, 4.0, nil]
feb: [2.0, 30.0, 61.0]
mar: [1.0, 80.0, 95.0]
echo df.select(col.station, sumHorizontal(col(float)).alias("total"),
maxHorizontal("jan", "feb", "mar").alias("wettest"),
coalesce(col.jan, col.feb).alias("first_reading"))
TBD
- WHEN
sumHorizontal([col.a, col.b], ignoreNulls = false)runs on a row wherebis null - THEN that row's sum is null
- WHEN
allHorizontalandanyHorizontalrun on a row holding true and false - THEN they give false and true
Generated columns
intRange(start, stop, step = 1, dtype = Int64) (or intRange(stop)) SHALL produce the integers from start up to stop excluded, linearSpace(start, stop, numSamples, closed) SHALL produce evenly spaced floats, and repeat(value, n) SHALL repeat a value n times.
echo newDataFrame().select(intRange(1950, 2026, 25).alias("year"),
linearSpace(0, 1, 4).alias("share"),
repeat("ENSO", 4).alias("index"))
TBD
- WHEN
intRange(0, 5, step = 0)is built - THEN
ValueErroris raised
Correlation
corr(a, b, correlationMethod = Pearson) SHALL return the Pearson or Spearman correlation of two columns as an aggregation, and cov(a, b, ddof = 1) their covariance.
let df = newDataFrame:
oni: [-1.0, 0.0, 0.5, 2.0]
world: [14.6, 14.8, 14.9, 15.2]
echo df.select(corr("oni", "world").round(3).alias("pearson"),
corr("oni", "world", Spearman).alias("spearman"))
TBD
- WHEN
corrruns on 1, 2, 3 and 2, 4, 6 - THEN the result is 1.0
Tasks
1. Implementation
- 1.1Horizontal functions and
coalesce - 1.2
intRange,linearSpace,repeat - 1.3
corrwithCorrelationMethod,cov - 1.4Tests in
tests/test_horizontal.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
570d956 Nanuq 0.4, changes 1-7: math, cumulative, rolling, value functions, horizontal, reshaping, time groupingFirst version: proposal.md, specs/horizontal-functions/spec.md, tasks.md
add-html-tables Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 6/6
- Archive
Proposal
Why
In nimib documents a DataFrame can only be shown as Polars' text table. That table is the reference output and stays the default in the dev log (it is also a check that Nanuq prints exactly what Polars prints). For pages where a real HTML table reads better, Nanuq should offer the same HTML table that Python Polars shows in Jupyter.
This takes up the BACKLOG.md entry "nimib integration" (Ecosystem).
What Changes
- New
toHtml(df, maxRows = 10, maxCols = 75): string, a port of Python Polars'DataFrame._repr_html_. It returns the same HTML, with the same information: shape: (344, 8)above the table, with_thousand separators;- a header row of column names and a row of dtypes (
str,i64,f64, …); - when there are more rows or columns than the limits, the first and last ones around a
…row or column (10 rows show as 5,…, 5); - each cell formatted by Polars itself, as Python shows it: floats as in the text table, strings in quotes and cut after 30 characters with
…, nulls asnull; - HTML escaping, and the small
<style>block anddataframeclass Python emits. - It works in any HTML context. In nimib it is used as
nbRawHtml: df.toHtml, so Nanuq does not depend on nimib. The Nanuq theme gets CSS fortable.dataframe. - A new bridge function returns one cell formatted the way Python's
get_fmtdoes (AnyValue's Display, with the string cut). - The dev log uses it sparingly: one short section in "How Nanuq works" shows the same result as text and as HTML. Every other output stays Polars' text table.
Capabilities
New Capabilities
None.
Modified Capabilities
dataframe-api: an added requirement for HTML tables.native-bridge: an added requirement for formatted cells.
Differences from Polars
- Rust has no HTML output; this follows Python.
- Python calls it
_repr_html_and reads the limits from thePOLARS_FMT_MAX_ROWS,POLARS_FMT_MAX_COLSandPOLARS_FMT_STR_LENenvironment variables. Nanuq names ittoHtmland takes the row and column limits as parameters with Python's defaults (10 and 75); the string length is fixed at Python's default (30). ThePOLARS_FMT_TABLE_HIDE_*switches are not supported. - HTML vs text table. As in Python, the HTML defaults differ from the text table: the text table shows at most 8 columns, the HTML table 75. Rows match (10).
Impact
src/rust/src/lib.rsandsrc/nanuq/ffi.nim: one new function. This changes the Rust library, so it needs a library build.lib-v0.1.0is already released without it, sotoHtmlships with the next library release (e.g.lib-v0.1.1); until then it works only with a local cargo build.src/nanuq.nim:toHtml.docs/nanuqtheme.nim: table CSS.docs/blog/how_nanuq_works.nim.- New tests in
tests/.
Spec changes
dataframe-api modified
HTML tables
toHtml(df, maxRows = 10, maxCols = 75) SHALL return the HTML that Python Polars' DataFrame._repr_html_ returns for the same data and limits: shape line, names and dtypes header rows, cells formatted by Polars, and … rows and columns when truncated.
- WHEN
toHtmlis called onpenguins() - THEN the result equals what Python Polars'
_repr_html_returns for the same CSV read withnull_values="NA"
- WHEN a DataFrame with 344 rows is rendered with
maxRows = 10 - THEN the body shows rows 0 to 4, a
…row, and rows 339 to 343
- WHEN a string cell holds
<b>and another cell is null - THEN the first is shown as
"<b>"and the second asnull
Unchanged in this spec: Automatic memory management, Building and reading data, Reading columns by type, Expressions and lazy queries, Block syntax for building a DataFrame, Column shorthand, True division, Errors as PolarsError
native-bridge modified
Formatted cells
The bridge SHALL return a single cell as text formatted by Polars, as Python Polars' get_fmt does: the value's display form, with strings in quotes and cut to a given number of characters followed by ….
- WHEN a cell holding 5076.016260162602 is formatted
- THEN the text is the same as in Polars' text table,
5076.01626
- WHEN a string of 40 characters is formatted with a limit of 30
- THEN the text is a quote, its first 30 characters and
…
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Nim declarations mirror the C ABI, Linking the static library, Columns cross in bulk, Library version check, Polars version matches a py-polars release
Tasks
1. Bridge
- 1.1Add a Rust function formatting one cell (by column and row, with a string length limit) like py-polars'
get_fmt, returning the needed length when the buffer is too small; mirror it inffi.nim; verifycargo build --releasepasses
2. toHtml
- 2.1Add
toHtml(df, maxRows = 10, maxCols = 75)tosrc/nanuq.nim, ported from py-polars'HTMLFormatter/NotebookFormatter; verify with tests for truncation, escaping, nulls and a wide frame - 2.2Compare with Python: render penguins and a small mixed-dtype frame in Python Polars (if available in the container) and check the HTML is identical; otherwise compare against stored expected output; record the Polars version used
3. Dev log
- 3.1Add
table.dataframeCSS todocs/nanuqtheme.nim(light and dark) - 3.2Add one short section to "How Nanuq works" showing a result as text and as
nbRawHtml: summary.toHtml; leave every other output as text; verify the post renders and republish its artifact - 3.3Check CI is green on the PR
Workflow follow-up
Revisions
ed08e02 Archive the dev-log index, HTML tables and Datamancer interop changesFirst version: .openspec.yaml, proposal.md, specs/dataframe-api/spec.md, specs/native-bridge/spec.md, tasks.md
add-inspection-and-config Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 6/6
- Archive
Proposal
Why
The first thing the 0.3 explainer does with a new table is look at it: one line per column with glimpse, summary statistics with describe, and all 36 races of the season printed at once, which needs more than Polars' default of 8 rows. Nanuq has none of these. Python Polars has all three (glimpse, describe, pl.Config), and Rust Polars reads its table limits from environment variables that Python's Config sets.
This is the second change of the 0.3 release, following the dev log "Designing Nanuq 0.3" (section 7) and Pietro's follow-up on 2026-10-31: keep the four setTbl*-style setters (one line with semicolons is fine) and also offer setConfig(...) and a scoped withConfig(...).
What Changes
glimpse(df, maxItemsPerColumn = 10, maxColnameLength = 50): string, Python's layout:Rows:andColumns:, then$ name <dtype> v1, v2, ...per column, strings quoted as Python'sreprdoes. It returns the text (echo df.glimpse) instead of printing.describe(df, percentiles = [0.25, 0.5, 0.75], interpolation = Nearest): DataFrame: astatisticcolumn (count,null_count,mean,std,min, the percentiles,max) and one column per input column, f64 for numeric and boolean columns, str for the others, built from expressions as Python Polars does. Also onLazyFrame.- Display config, through the environment variables Rust Polars reads at every print:
- setters
setTblRows(n),setTblCols(n),setTblWidthChars(n),setFmtStrLengths(n);-1means no limit,none(int)restores the default; setConfig(tblRows = 12, tblCols = 10, tblWidthChars = 120, fmtStrLengths = 60), where an option left out stays as it is;resetConfig()restores every default;withConfig(tblRows = 40): bodyapplies the options for the block and restores the previous values afterwards, also when the block raises.
Capabilities
New Capabilities
inspection:glimpse,describeand the display config.
Modified Capabilities
None.
Differences from Polars
Expected differences from Polars' Rust and Python APIs:
glimpsereturns a string and never prints; Python prints by default and returns a string only withreturn_type="string".return_type="frame"is left out (it needs List columns). Rust Polars has noglimpse.describefollows Python's output. Rust Polars droppeddescribe, so Nanuq builds it from expressions in Nim, the way Python'sLazyFrame.describedoes. Python's thousands separator for counts in string columns is not applied (Nanuq has no thousands separator setting yet). Temporal columns get their statistics with the temporal change.- Config is a set of procs and a
withConfigblock, Nim's version of Python'spl.Configused as a function, a context manager or a decorator (no decorator). Only the four table options are covered; Python's other options (tbl_formatting,float_precision,thousands_separator, ...) are left for later. Rust Polars has no config API, only the environment variables (POLARS_FMT_MAX_ROWS,POLARS_FMT_MAX_COLS,POLARS_TABLE_WIDTH,POLARS_FMT_STR_LEN), which Nanuq sets. - Names follow Python in camelCase:
set_tbl_rows→setTblRows,max_items_per_column→maxItemsPerColumn.
Impact
src/nanuq.nim:glimpse,describe, the config procs and thewithConfigmacro. No change to the C ABI.tests/test_inspection.nim(new), added tonanuq.nimbleand.gitignore.- README lists the new procs.
Spec changes
inspection modified
glimpse
glimpse(df, maxItemsPerColumn = 10, maxColnameLength = 50) SHALL return, as a string, the lines Rows: <height> and Columns: <width>, then one line per column: $ <name> <<dtype>> <values>, with names left-aligned and dtypes right-aligned to a common width, and the first maxItemsPerColumn values joined by ", ". Nulls SHALL be null, booleans True/False, and strings quoted as Python's repr quotes them. Names longer than maxColnameLength SHALL be cut and end with ….
let df = newDataFrame:
rider: ["Pogačar", "Seixas", "Van der Poel"]
wins: [22, 8, nil]
pro: [true, false, true]
race: ["Giro d'Italia", "Tour", "Vuelta"]
echo df.glimpse
Rows: 3
Columns: 4
$ rider <str> 'Pogačar', 'Seixas', 'Van der Poel'
$ wins <i64> 22, 8, null
$ pro <bool> True, False, True
$ race <str> "Giro d'Italia", 'Tour', 'Vuelta'
- WHEN a column of 100 rows is glimpsed with
maxItemsPerColumn = 3 - THEN its line shows the first 3 values only
- WHEN a column named with 60 characters is glimpsed
- THEN its line shows the first 49 characters followed by
…
describe
describe(percentiles = [0.25, 0.5, 0.75], interpolation = Nearest) on DataFrame and LazyFrame SHALL return a DataFrame with a statistic column holding count, null_count, mean, std, min, one row per percentile (labelled as 25%) and max, followed by one column per input column: f64 for numeric and boolean columns, str for the others, and null where a statistic does not apply.
let df = newDataFrame:
rider: ["Pogačar", "Seixas", "Van der Poel"]
wins: [22, 8, nil]
pro: [true, false, true]
echo df.describe
shape: (9, 4)
┌────────────┬──────────────┬──────────┬──────────┐
│ statistic ┆ rider ┆ wins ┆ pro │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 ┆ f64 │
╞════════════╪══════════════╪══════════╪══════════╡
│ count ┆ 3 ┆ 2.0 ┆ 3.0 │
│ null_count ┆ 0 ┆ 1.0 ┆ 0.0 │
│ mean ┆ null ┆ 15.0 ┆ 0.666667 │
│ std ┆ null ┆ 9.899495 ┆ null │
│ min ┆ Pogačar ┆ 8.0 ┆ 0.0 │
│ 25% ┆ null ┆ 8.0 ┆ null │
│ 50% ┆ null ┆ 22.0 ┆ null │
│ 75% ┆ null ┆ 22.0 ┆ null │
│ max ┆ Van der Poel ┆ 22.0 ┆ 1.0 │
└────────────┴──────────────┴──────────┴──────────┘
- WHEN
describe(percentiles = [0.1, 0.9])runs - THEN the statistic column holds
count,null_count,mean,std,min,10%,90%andmax
- WHEN a frame with a string and a boolean column is described
- THEN mean, std and percentiles are null for the string column, and std and percentiles for the boolean one
- WHEN
newDataFrame().describeruns - THEN
NanuqErroris raised
Display config
The API SHALL set how tables print with setTblRows(n), setTblCols(n), setTblWidthChars(n) and setFmtStrLengths(n), where -1 means no limit and none(int) restores Polars' default; with setConfig(tblRows, tblCols, tblWidthChars, fmtStrLengths), where options left out are unchanged; and with resetConfig(), which restores every default. The settings SHALL apply to every later $ of a DataFrame.
let df = newDataFrame(series("n", [1, 2, 3, 4, 5, 6]))
setTblRows(4); setFmtStrLengths(10)
echo df
setConfig(tblRows = 2, tblCols = 5)
echo df
resetConfig()
shape: (6, 1)
┌─────┐
│ n │
│ --- │
│ i64 │
╞═════╡
│ 1 │
│ 2 │
│ … │
│ 5 │
│ 6 │
└─────┘
shape: (6, 1)
┌─────┐
│ n │
│ --- │
│ i64 │
╞═════╡
│ 1 │
│ … │
│ 6 │
└─────┘
- WHEN
setTblRows(-1)is called and a frame of 50 rows is printed - THEN all 50 rows are shown
- WHEN
setTblRows(2)and thenresetConfig()are called - THEN a frame of 10 rows prints all 10 rows again
Scoped display config
withConfig(options): body SHALL apply the named options (tblRows, tblCols, tblWidthChars, fmtStrLengths) while body runs, and SHALL restore the previous settings afterwards, also when body raises.
let df = newDataFrame(series("n", [1, 2, 3, 4, 5, 6]))
withConfig(tblRows = 2):
echo df
echo df.shape, " ", ($df).count('\n')
shape: (6, 1)
┌─────┐
│ n │
│ --- │
│ i64 │
╞═════╡
│ 1 │
│ … │
│ 6 │
└─────┘
(6, 1) 11
- WHEN the body of
withConfig(tblRows = 2)raises - THEN the exception propagates and the row limit is back to its previous value
Unchanged in this spec: Describe prints temporal values as Python, Table formatting options
Design
Design
Context
Rust Polars' table formatter (polars-core/src/fmt.rs) reads POLARS_FMT_MAX_ROWS, POLARS_FMT_MAX_COLS, POLARS_TABLE_WIDTH and POLARS_FMT_STR_LEN with std::env::var every time a frame is formatted; negative values mean no limit. Python's pl.Config.set_tbl_rows and friends set these variables. Python's glimpse and describe are written in Python over expressions.
Decisions
Config through the process environment
Nim's putEnv/delEnv change the same process environment that Rust's std::env::var reads, so no ABI function is needed. withConfig saves the four variables (value or absent), applies the options with setConfig, runs the block in try/finally, and restores them. It is a macro over varargs[untyped] because a template with defaulted int | Option[int] parameters followed by a block does not match named arguments.
Options take int | Option[int]. In the setters, none(int) restores the default; in setConfig and withConfig, an option left out is left unchanged.
glimpse in Nim
Values are the first maxItemsPerColumn rows, read as Option[string], which uses Polars' formatting for non-string columns. Python formats them with str(), so booleans become True/False; string values are quoted like Python's repr (single quotes, double quotes when the value holds a single quote and no double quote, backslash escapes). Names longer than maxColnameLength are cut with ….
describe in Nim
For each column, the applicable metric expressions are selected in one query (count, nullCount, mean, std, min, quantiles, max), each cast to f64 for numeric and boolean columns and to str otherwise; the others are null in the result. The single result row is then reshaped in Nim into the output frame. Percentile labels use Python's f"{q * 100:g}%".
Risks / Trade-offs
- The environment is process-wide, so config is not thread-local, as in Python.
Tasks
1. Nim API
- 1.1Add
glimpsewith Python's layout and value formatting - 1.2Add
describeon DataFrame and LazyFrame withpercentilesandinterpolation - 1.3Add
setTblRows,setTblCols,setTblWidthChars,setFmtStrLengths,setConfig,resetConfigand thewithConfigmacro - 1.4Write
tests/test_inspection.nim(glimpse truncation and quoting, describe on numeric, bool and string columns and custom percentiles, setters,withConfigrestoring after an exception); add it tonanuq.nimbleand.gitignore
2. Docs and integration
- 2.1README lists the new procs;
nimble testandnimble specexamplespass - 2.2Archive the change and add CHANGELOG lines
Revisions
3280788 OpenSpec add-inspection-and-config: glimpse, describe, display configFirst version: design.md, proposal.md, specs/inspection/spec.md, tasks.md
add-joins-and-concat Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 10/10
- Archive
Proposal
Why
Nanuq can query one table, but real analyses combine several: measurements with a lookup table, this month's file with last month's, a set of keys with the rows that match them. Joins and concatenation are the most used Polars verbs that Nanuq still lacks, and the 0.2 plan puts them right after data types (casting key columns to a common type is the usual fix when a join refuses mismatched keys).
This change takes up the BACKLOG.md entry "Joins" (API) and adds concatenation, which has no entry. Joins are the first verbs with many option values, so the change also settles, for all of Nanuq, how option values are spelled in Nim (decided by Pietro on 2026-10-31 after a design note comparing strings, prefixed enums, pure enums and one proc per variant). It is the second change of the 0.2 release (see the Polars coverage map, area "Joins and concatenation").
What Changes
- New
joinon LazyFrame and DataFrame, with Polars' join types: inner, left, right, full, semi, anti and cross. - Keys by name (
on = ["station"]), or different names on each side (leftOn = ["id"], rightOn = ["station_id"]), as strings or expressions. howtakes aJoinTypevalue:how = Left.- Options as named parameters with Polars' defaults:
suffix = "_right",validate(JoinValidation, defaultManyToMany),nullsEqual = false,coalesce(none(bool)= Polars' per-join-type default), andmaintainOrder(MaintainOrderJoin, defaultNone: no order guaranteed). - A cross join takes no keys:
a.join(b, how = Cross). - New
concatof several LazyFrames or DataFrames, withhowaConcatMethod:Vertical(default),VerticalRelaxed,Horizontal,Diagonal,DiagonalRelaxed. - API convention for option values (all of Nanuq): a closed set of option values is a pure enum (
{.pure.}) with the Rust Polars type name and its PascalCase variant names, e.g.JoinType.Left, written bare (how = Left) where the type is known. The convention is recorded as a new spec, inopenspec/config.yaml(so every later proposal follows it) and in the README. - BREAKING:
DataTypeKindfollows the convention:dkInt64becomesDataTypeKind.Int64,dkOtherbecomesDataTypeKind.Other. TheDataTypeconstants (Int64,String, ...) are unchanged and still what users normally write. - Polars features
semi_anti_join,cross_joinanddiagonal_concatare compiled in. The ABI stays0.2.0-dev(released aslib-v0.2.0with the rest of 0.2).
Capabilities
New Capabilities
combining-frames: joins and concatenation of DataFrames and LazyFrames.api-conventions: naming rules that apply across the Nim API, starting with how option values are spelled.
Modified Capabilities
data-types:DataTypeKindvalues become pure PascalCase (DataTypeKind.Other).native-bridge: the enums that must keep the same order in Rust andffi.nimnow include the join and concat enums.
Differences from Polars
Expected differences from Polars' Rust and Python APIs:
- Enums instead of strings. Python's
how="left",validate="1:m",maintain_order="left_right"andpl.concat(how="diagonal")become pure enums with Rust's names:JoinType.Left,JoinValidation.OneToMany,MaintainOrderJoin.LeftRight, andConcatMethod.Diagonal. In a typed context the bare value works (how = Left); elsewhere it must be qualified, as in Rust. Two enums may share a value name (JoinType.Left,MaintainOrderJoin.Left), as in Rust. ConcatMethodis Nanuq's. Rust has no single enum for concat (it has separate functions andUnionArgsflags); the name and the values follow Python'showstrings in PascalCase.coalesceis anOption[bool](Python'sNone,True,False).- No keyword-only checks. Python rejects
ontogether withleft_on; Nim overloads make the two forms separate procs, so mixing them doesn't compile. - Not in this change:
join_asof,join_where,merge_sorted,update,vstack/hstack/extend,pl.concat(how="align"), Series concatenation, andconcat'srechunk/parallelflags. They stay in the coverage map for later releases. - Names follow Polars in camelCase:
left_on→leftOn,right_on→rightOn,nulls_equal→nullsEqual,maintain_order→maintainOrder.
Impact
src/rust/src/lib.rs:#[repr(C)]enumsNqJoinType,NqJoinValidation,NqMaintainOrderJoin,NqConcat;nq_lf_joinandnq_lf_concat.Cargo.tomladds the three Polars features. The Rust library is rebuilt in CI (the first run takes about 10 minutes).src/nanuq/ffi.nim,src/nanuq.nim: the matching declarations, the enums and the procs;DataTypeKindbecomes pure (its uses insrc/nanuq.nimand the tests are updated).openspec/config.yaml: a proposal rule pointing at theapi-conventionsspec.tests/test_combining.nim: every join type, key forms, options, and every concat method.README.md: the API list mentionsjoinandconcat, and a short "Conventions" section states the option-value rule.
Spec changes
api-conventions modified
Option values are pure enums with Rust Polars names
A parameter that takes one of a closed set of option values SHALL use a {.pure.} enum whose type name and PascalCase value names are those of the corresponding Rust Polars enum (e.g. JoinType.Left for JoinType::Left). When Rust Polars has no such enum, Nanuq SHALL name one after Python Polars' parameter strings, in PascalCase. Strings SHALL NOT be used for closed sets of options. Internal C ABI enums in ffi.nim keep their Nq/nq prefixes and are exempt.
- WHEN user code passes
how = Lefttojoin - THEN it compiles and means
JoinType.Left
- WHEN user code passes
how = Left, maintainOrder = Left - THEN each resolves to its own enum's value, as in Rust
- WHEN user code writes
let x = Leftwith several enums exportingLeft - THEN compilation fails as ambiguous, and
let x = JoinType.Leftcompiles
The conventions are documented
The README SHALL state the API conventions (camelCase Polars names, pure enums with Rust names for option values), and every OpenSpec proposal SHALL follow them, listing any exception in its "Differences from Polars" section.
- WHEN a proposal adds a parameter with a closed set of values
- THEN it uses the Rust Polars enum name and values as a pure enum, or explains why not
Unchanged in this spec: Python's method parameter is how, Parameters that take several types use converter types
combining-frames modified
Joins
The API SHALL join two LazyFrames or two DataFrames with join, with how one of a JoinType: Inner (default), Left, Right, Full, Semi, Anti or Cross. Keys SHALL be given as on (same names on both sides) or leftOn and rightOn, as column names or expressions. A cross join SHALL take no keys.
- WHEN a frame with keys 1, 2, 3 is left-joined on
kto a frame with keys 1, 3 - THEN the result has three rows, and the right side's columns are null for key 2
- WHEN the same frames are semi-joined and anti-joined
- THEN the semi join keeps the rows with keys 1 and 3, and the anti join keeps the row with key 2, with only the left columns
- WHEN frames are joined with
leftOn = ["id"]andrightOn = ["station_id"] - THEN rows are matched on those columns
- WHEN a 2-row frame is joined to a 3-row frame with
how = Cross - THEN the result has 6 rows
- WHEN
joinis called without keys and a join type other thanCross - THEN
NanuqErroris raised
Join options
join SHALL accept, with Polars' defaults: suffix ("_right") for clashing column names, validate (JoinValidation: ManyToMany, or ManyToOne, OneToMany, OneToOne), nullsEqual (false), coalesce (none(bool) for Polars' per-join-type default) and maintainOrder (MaintainOrderJoin: None, or Left, Right, LeftRight, RightLeft).
- WHEN both frames have a non-key column
vandsuffix = "_b" - THEN the result has columns
vandv_b
- WHEN the right frame has a duplicate key and
validate = ManyToOne - THEN
NanuqErroris raised when the query runs
- WHEN both frames have a null key, joined with
nullsEqual = true - THEN the null keys match each other; with the default they don't
- WHEN a left join runs with
maintainOrder = Left - THEN the result rows follow the left frame's order
Concatenation
The API SHALL concatenate a list of LazyFrames or DataFrames with concat, with how a ConcatMethod: Vertical (default, same schema), VerticalRelaxed (cast to common supertypes), Horizontal (side by side), Diagonal (union of columns, missing ones null) or DiagonalRelaxed. An empty list SHALL raise NanuqError.
- WHEN two frames with the same columns and 2 and 3 rows are concatenated
- THEN the result has 5 rows in input order
- WHEN frames whose column
ais i64 in one and f64 in the other are concatenated - THEN
VerticalraisesNanuqErrorandVerticalRelaxedreturnsaas f64
- WHEN a frame with columns
a, band one withb, care concatenated diagonally - THEN the result has columns
a, b, c, with nulls where a frame had no column
- WHEN a frame with column
aand one with columnbare concatenated horizontally - THEN the result has columns
aandb
data-types modified
DataType values
Casting
Unchanged in this spec: DataType constants and predicates, Schemas, Nim types map to DataType, Full-range UInt64
native-bridge modified
Nim declarations mirror the C ABI
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release
Design
Design
Context
Lazy verbs cross the ABI as functions that borrow a LazyFrame and return a new one (nq_lf_filter, nq_lf_cast, ...). Lists of expressions are passed as a pointer and a length, and enums as #[repr(C)] integers mirrored in ffi.nim. DataFrame verbs are eager shortcuts: df.lazy.<verb>.collect. In Polars 0.55, LazyFrame::join(other, left_on, right_on, JoinArgs) takes JoinArgs { how, validation, suffix, nulls_equal, coalesce, maintain_order, .. }, and concatenation is concat(lfs, UnionArgs), concat_lf_diagonal and concat_lf_horizontal.
Goals / Non-Goals
Goals:
- Every equi-join type and option Python Polars exposes, with the same defaults.
- One Rust function per verb, so options are added without new ABI functions.
- Joins and concat read naturally from Nim:
a.join(b, on = ["k"], how = Left). - One rule for option values that every later change reuses.
Non-Goals:
- As-of and inequality joins (later releases, need more features and sorted keys).
- Changing Polars' defaults, such as making join order deterministic by default.
Decisions
One join function with all options
nq_lf_join(left, right, left_on: *const *const Expr, n_left, right_on: *const *const Expr,
n_right, how: NqJoinType, suffix: *const c_char, validate: NqJoinValidation,
nulls_equal: bool, coalesce: i32 /* -1 default, 0 keep, 1 coalesce */,
maintain_order: NqMaintainOrderJoin) -> *mut LazyFrame
Nim builds the key expressions (col(name) for strings) and passes both lists; for on the same list goes on both sides. A cross join passes empty lists, and Rust rejects keys on a cross join and a missing key on any other join with a clear error.
- Why: a single entry point keeps the ABI small; the options map one to one onto
JoinArgs. - Alternative: an options struct across the ABI. More layout to keep in sync for no gain at this size.
Nim procs
proc join*(lf, other: LazyFrame, on: openArray[string], how = JoinType.Inner,
suffix = "_right", validate = JoinValidation.ManyToMany, nullsEqual = false,
coalesce = none(bool), maintainOrder = MaintainOrderJoin.None): LazyFrame
proc join*(lf, other: LazyFrame, leftOn, rightOn: openArray[string], how = JoinType.Inner, ...)
proc join*(lf, other: LazyFrame, on: openArray[Expr], ...) # and leftOn/rightOn
proc join*(lf, other: LazyFrame, how: JoinType, suffix = "_right", ...) # cross join
plus the same on DataFrame. on / leftOn / rightOn are named, so a.join(b, on = ["k"]) and a.join(b, leftOn = ["id"], rightOn = ["sid"]) both read clearly. The keyless overload is meant for how = Cross and raises NanuqError for any other join type.
Option values: pure enums with Rust's names (Nanuq-wide)
type
JoinType* {.pure.} = enum Inner, Left, Right, Full, Semi, Anti, Cross
JoinValidation* {.pure.} = enum ManyToMany, ManyToOne, OneToMany, OneToOne
MaintainOrderJoin* {.pure.} = enum None, Left, Right, LeftRight, RightLeft
ConcatMethod* {.pure.} = enum Vertical, VerticalRelaxed, Horizontal, Diagonal, DiagonalRelaxed
The rule, for every option type now and later: use the Rust Polars enum's type name and variant names, as a {.pure.} enum. Only when Rust has no enum (as for concat) does Nanuq name one, following Python's strings in PascalCase.
- Why: NEP 1 allows unprefixed values only for pure enums, in PascalCase, and the stdlib does the same (
SortOrder.Ascending). Rust's names need no invention, map one to one onto Polars' Rust docs, and may repeat across types (JoinType.Left,MaintainOrderJoin.Left) because a pure value is resolved from the expected type, or qualified. Checked with Nim 2.2.4:join(how = Left, maintainOrder = Left)compiles and picks each type's value;let x = Leftis ambiguous and must be qualified. - Alternatives considered (design note of 2026-10-31): strings like Python (runtime typos, no completion, unusual in Nim); short prefixes
jtLeft(NEP 1's default, cryptic, far from Polars); long prefixesjoinLeft(verbose, needs invented prefixes); bare camelCaseleft(against NEP 1, forced theleftOrderworkaround); one proc per variantleftJoin(still needs enums for the other options; possible later as sugar). DataTypeKindfollows the rule:DataTypeKind.Int64,DataTypeKind.Other. Pure enum values and theDataTypeconstants of the same name coexist: a bareInt64where aDataTypeis expected picks the constant (checked).- The enums in
ffi.nim(NqJoinType, ...) are internal and keep theirnqprefix.
Concat
nq_lf_concat(lfs: *const *const LazyFrame, n, how: NqConcat) -> *mut LazyFrame: Vertical and VerticalRelaxed call concat with to_supertypes false or true; Diagonal and DiagonalRelaxed call concat_lf_diagonal with the same flag; Horizontal calls concat_lf_horizontal. In Nim, concat(frames: openArray[LazyFrame], how = ConcatMethod.Vertical) and the DataFrame version (lazy, concat, collect). An empty list raises NanuqError, as in Polars.
Risks / Trade-offs
- Capitalised bare values in the namespace.
Left,Inner,Vertical, ... are exported. Overload resolution by expected type makes clashes harmless in typed contexts; the qualified form is the escape hatch. - Breaking
DataTypeKind. Only code that names kinds (case t.kind) changes; the constants users write stay the same. Nanuq has no outside users yet. - Unordered joins by default. Following Polars, a join's row order is not guaranteed unless
maintainOrderis set. Tests and docs sort or set it. The README mentions it. - Binary size. Three more Polars features; small next to the current library.
Tasks
1. Bridge
- 1.1Add Polars features
semi_anti_join,cross_joinanddiagonal_concattosrc/rust/Cargo.toml(version stays0.2.0-dev); verifycargo build --releasepasses - 1.2Add
#[repr(C)]NqJoinType,NqJoinValidation,NqMaintainOrderJoinandnq_lf_join(keys checks for cross and non-cross joins); mirror them inffi.nim - 1.3Add
NqConcatandnq_lf_concat(vertical, relaxed, horizontal, diagonal); mirror them inffi.nim; verifycargo build --releasepasses
2. Nim API
- 2.1Make
DataTypeKinda pure enum with PascalCase values (DataTypeKind.Int64,DataTypeKind.Other); updatesrc/nanuq.nim,datamancer.nimand tests; verifynimble testpasses and a bareInt64still means theDataTypeconstant - 2.2Add the pure enums
JoinType,JoinValidation,MaintainOrderJoin,ConcatMethod, in the same order as the Rust enums - 2.3Add
joinon LazyFrame and DataFrame foronandleftOn/rightOn(strings and expressions) and the keyless cross join, with all options; verify every join type, both key forms, suffix, validation failure,nullsEqual,coalesce,maintainOrder, and thathow = Left, maintainOrder = Leftcompiles - 2.4Add
concatfor LazyFrames and DataFrames; verify every method, the strict vertical failure and the empty list error
3. Conventions, docs and integration
- 3.1Add a proposal rule to
openspec/config.yamlthat option values follow theapi-conventionsspec - 3.2Add a "Conventions" section to the README (Polars names in camelCase, pure enums with Rust names for option values, qualify outside typed contexts) and list
joinandconcatin "What is there" (with the note that join order is not guaranteed withoutmaintainOrder); verifynimble testandnimble examplepass - 3.3Check that CI is green on the PR, including the Rust rebuild
Workflow follow-up
Revisions
2ef7787 Add joins and concatenation (implements add-joins-and-concat)First version: .openspec.yaml, design.md, proposal.md, specs/api-conventions/spec.md, specs/combining-frames/spec.md, specs/data-types/spec.md, specs/native-bridge/spec.md, tasks.md
add-json-io Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
JSON is the most common nested data format: read_json blocks 7 book sections and scan_ndjson/read_ndjson 7 more, and the coverage map says JSON is useful once nested dtypes exist, which they now do. It comes from the BACKLOG.md entry "More IO" (NDJSON; Excel, sinks and cloud storage stay there).
It is the fifth change of the 0.5 release.
What Changes
readJson(path or Stream): a JSON array of objects (or an object of columns).readNdjson(path or Stream)andscanNdjson(path): newline-delimited JSON, one object per line, eager and lazy (globs,nRows, row index).- Both take
schema(all columns) orschemaOverrides(some),inferSchemaLengthandignoreErrors. writeJson(path or Stream)writes a JSON array of row objects,writeNdjsonone object per line;toJson/toNdjsongive the text.
Capabilities
New Capabilities
json-io: reading and writing JSON and NDJSON.
Differences from Polars
- Python's
write_json()without a file returns the text; Nanuq hastoJsonfor that, sowriteJsonalways writes. schemaandschemaOverridesare{"name": dtype}pairs, as inreadCsv.- No cloud storage options.
Impact
src/rust/src/lib.rsandsrc/nanuq/ffi.nim:nq_df_read_json,nq_lf_scan_ndjson,nq_df_write_json.src/nanuq.nim: the readers and writers.- New
tests/test_json.nim.
Spec changes
json-io modified
Reading JSON
readJson(source) SHALL read a JSON array of objects (one row each) from a file path or a Stream, and readNdjson(source) newline-delimited JSON, with nested values becoming List and Struct columns. schema SHALL fix all column types, schemaOverrides some of them, inferSchemaLength SHALL bound the rows used to infer the rest, and ignoreErrors SHALL read values that do not parse as null.
import std/streams
let json = """[{"bear": "Ada", "cubs": ["Bo"], "den": {"lat": 78.2}},
{"bear": "Cy", "cubs": [], "den": {"lat": 79.0}}]"""
let df = readJson(newStringStream(json))
echo df
echo readNdjson(newStringStream("{\"a\": 1}\n{\"a\": 2}\n"), schemaOverrides = {"a": Float64})
TBD
- WHEN a file that is not JSON is read with
readJson - THEN
ComputeErroris raised
Scanning NDJSON
scanNdjson(path) SHALL read newline-delimited JSON files lazily (a path or a glob), with nRows, rowIndexName and rowIndexOffset and the schema options of readNdjson.
let path = getTempDir() / "bears.ndjson"
writeFile(path, "{\"bear\": \"Ada\", \"kg\": 410}\n{\"bear\": \"Bo\", \"kg\": 380}\n")
echo scanNdjson(path, rowIndexName = "i").filter(col("kg") > 400).collect
TBD
- WHEN a file of 3 lines is scanned with
nRows = 2 - THEN the frame has 2 rows
Writing JSON
writeJson(dest) SHALL write a frame as a JSON array of row objects to a path or a Stream, writeNdjson(dest) one object per line, and toJson/toNdjson SHALL return the same text; reading it back SHALL give the same frame.
let df = newDataFrame:
bear: ["Ada", "Bo"]
cubs: [@["Cy"], @[]]
echo df.toJson
echo df.toNdjson
TBD
- WHEN a frame with list and struct columns is written with
writeNdjsonand read withreadNdjson - THEN the result equals the frame
Tasks
1. Implementation
- 1.1Crate: JSON reader, NDJSON scan, JSON writer
- 1.2
readJson,readNdjson,scanNdjson,writeJson,writeNdjson,toJson,toNdjson - 1.3Tests in
tests/test_json.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
f27d0dd 0.5: JSON and NDJSON IO (add-json-io)First version: proposal.md, specs/json-io/spec.md, tasks.md
add-list-namespace Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
With List columns in Nanuq (add-nested-dtypes) the next step is computing on them. The book ports use explode (11 sections), list.eval with element() (11), concat_list (6) and list.first, list.get, list.len, list.sum (3 to 6 each), and the Polars coverage map puts the list namespace at P1.
It is the second change of the 0.5 release.
What Changes
e.list, a namespace likee.str: aggregations (len,sum,min,max,mean,median,std,var,first,last,argMin,argMax,nUnique,any,all), access (get,gather,gatherEvery,slice,head,tail,contains,countMatches,join), transforms (sort,reverse,unique,dropNulls,diff,shift,sample,filter,union,setDifference,setIntersection,setSymmetricDifference,toArray,toStruct), andevalandaggwithelement().explodeandimplodeon expressions,list.explode,explode(columns)on frames (eager and lazy, withemptyAsNullandkeepNulls), andconcatList(exprs).
Capabilities
New Capabilities
list-functions: the list namespace, explode, implode and concatList.
Differences from Polars
list.contains,countMatchesand the set operations take a Nim value or an expression, aslitwould turn it.list.sampletakesnorfractionas overloads (Python has both as keyword arguments).toStruct(fields)takes the field names; Python also takes a function or a length, and itsn_field_strategyis left out.unionis spelledunion(Python'sset_unionis an alias for it).- No
listnamespace on Series yet: uses.eval(col(s.name).list.len). filter(predicate)is Python'slist.filter, built onevalas in Polars.
Impact
src/rust/src/lib.rsandsrc/nanuq/ffi.nim:nq_expr_list(one entry point with an op code, likenq_expr_str),nq_expr_explode,nq_expr_implode,nq_concat_list,nq_lf_explode.src/nanuq.nim:ListNameSpace.- New
tests/test_lists.nim.
Spec changes
list-functions modified
List aggregations and access
e.list SHALL give a namespace whose methods work on each list of a List (or Array) column: len, sum, min, max, mean, median, std, var, first, last, argMin, argMax, nUnique, any, all give one value per list; get(i) (negative from the end), gather, gatherEvery, slice, head, tail pick values; contains(x), countMatches(x) and join(separator) compare or join them.
let df = newDataFrame:
cubs: [@[2, 1, 3], @[], @[4]]
names: [@["Ada", "Bo"], @["Cy"], @[]]
echo df.select(col("cubs").list.len.alias("n"), col("cubs").list.sum.alias("sum"),
col("cubs").list.get(0, nullOnOob = true).alias("first"),
col("cubs").list.contains(3).alias("has3"),
col("names").list.join(", ").alias("names"))
TBD
- WHEN
list.get(5)is evaluated on a list of 3 values withoutnullOnOob - THEN
ComputeErroris raised; withnullOnOob = truethe value is null
List transforms
e.list SHALL have sort, reverse, unique, dropNulls, diff, shift, sample, filter(predicate), the set operations union, setDifference, setIntersection and setSymmetricDifference with another list expression, toArray(width) and toStruct(fields), each giving a list (array or struct) per row.
let df = newDataFrame:
a: [@[3, 1, 3], @[2]]
b: [@[1, 5], @[2, 4]]
echo df.select(col("a").list.sort.alias("sorted"), col("a").list.unique(maintainOrder = true).alias("unique"),
col("a").list.union(col("b")).alias("union"),
col("a").list.filter(element() > 1).alias("gt1"))
TBD
- WHEN
list.toStruct(["x", "y"])is evaluated on lists of two values - THEN the result is a struct column with fields
xandy
Expressions on list elements
list.eval(e) SHALL evaluate e on the values of each list, with element() standing for them, and give a list per row; list.agg(e) SHALL do the same for an aggregation and give one value per row.
let df = newDataFrame:
weights: [@[410.0, 380.0], @[450.0, 470.0, 455.0]]
echo df.select(col("weights").list.eval(element().rank).alias("rank"),
col("weights").list.agg(element().max - element().min).alias("spread"))
TBD
- WHEN
element()is used in aselectthat is not insidelist.eval - THEN evaluating it raises a Polars error
Explode and implode
e.explode and e.list.explode SHALL give one row per list value, df.explode(columns) SHALL do the same for whole rows (eager and lazy; emptyAsNull and keepNulls default to true, as in Polars), e.implode SHALL collect a column into one list, and concatList(exprs) SHALL join values and lists of several columns into one list per row.
let df = newDataFrame:
den: ["A", "B", "C"]
cubs: [@["Ada", "Bo"], @[], @["Cy"]]
echo df.explode("cubs")
echo df.select(concatList(col("den"), col("cubs")).alias("all"))
echo df.select(col("den").implode)
TBD
- WHEN a frame with an empty list is exploded with
emptyAsNull = false - THEN that row is dropped instead of giving a null
Unchanged in this spec: Exploding several columns by name, Repeating values into lists, Seeds as plain ints
Tasks
1. Implementation
- 1.1Crate:
nq_expr_list, explode/implode,concat_list, frame explode - 1.2
ListNameSpaceand its methods;explode,implode,concatList - 1.3Tests in
tests/test_lists.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
5c0aadf 0.5: nested dtypes, list, struct and arr namespaces, nested stringsFirst version: proposal.md, specs/list-functions/spec.md, tasks.md
add-nested-dtypes Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 5/5
- Archive
Proposal
Why
Lists, arrays and structs are the Polars data types Nanuq does not model yet. They block most of the book sections still marked "not yet" (str.split, explode, unnest, struct.field, list.eval, value_counts, JSON), and the 0.4 changelog lists them as the main limitation. Before any list or struct function, Nanuq needs the types themselves, and a way to move nested values between Nim and Polars.
It is the first change of the 0.5 release ("Nested data and user code"). It comes from the BACKLOG.md entry "More dtypes" (lists and structs; decimals and binary stay there).
What Changes
DataTypegains the kindsList,ArrayandStruct, with constructorsList(Int64),Array(Float64, 3)(or a shape,Array(Int64, [2, 3])) andStruct({"x": Int64, "y": String}), accessorsinner,width,shapeandfields(a seq ofField, withnameanddtype), and Polars' names (list[i64],array[f64, 3],struct[2]).dataType(T)mapsseq[T]to List,array[N, T]to Array and objects and named tuples to Struct.- Nested columns from Nim:
series(name, values)and thenewDataFrameblock take seqs of seqs (@[@[1, 2], @[]]), arrays, objects and named tuples, at any depth, withOption(ornilin the block) for null rows andOptionelements for null values.toDataFrame(rows)takes objects with such fields.lit(@[1, 2])is a list literal. - Nested values back to Nim:
toList(column, seq[int]),toList(column, MyObject),Optionof these, the same on Series, cell readsdf[column, row, seq[string]], and row objects (rows(T)) whose fields are seqs or objects. - Casting to nested types:
col("a").cast(List(Int32)). - The C ABI passes data types as handles (
NqDataType), so nested types can be read and given at any depth, and builds nested Series from their parts (inner values and offsets, or fields).
Capabilities
New Capabilities
nested-data: List, Array and Struct data types and nested values between Nim and Polars.
Modified Capabilities
data-types: the type mapping covers seqs, arrays, objects and tuples.
Differences from Polars
- Struct values are Nim objects or named tuples, chosen by the caller; Python uses dicts. A struct literal in the block is a named tuple,
(x: 1, y: 2.0), not{"x": 1}. Struct(...)takes{"name": dtype}pairs or a seq ofField; Python also takes a dict or a list ofpl.Field, which are the same thing.Array(inner, [2, 3])takes a shape as an array of ints; Python takes a tuple.- Reading a struct field that is missing from the object raises
ColumnNotFoundError(asrowsdoes for columns); extra struct fields are ignored. - An empty Nim seq has a static element type, so
@[]columns are neverlist[null], unlike Python'spl.Series([[]]).
Impact
- C ABI: data type handles (
nq_dtype_*) replace the per-property column functions;NqDtypeSpecgains a nested handle; newnq_series_list_from_parts,nq_series_array_from_inner,nq_series_struct_from_fieldsand readersnq_series_list_offsets,nq_series_inner,nq_series_struct_field,nq_series_validity.src/rust/src/lib.rsandsrc/nanuq/ffi.nimtogether. src/nanuq.nim: types, constructors, generic readers and writers.- Polars crate features for 0.5 are all added here (list_, array_, json, sql, meta, ...).
- New
tests/test_nested.nim.
Spec changes
data-types modified
Nim types map to DataType
Unchanged in this spec: DataType values, DataType constants and predicates, Schemas, Casting, Full-range UInt64
nested-data modified
Nested data types
DataType SHALL have the kinds List, Array and Struct, built by List(inner), Array(inner, width) (or a shape, Array(Int64, [2, 3])) and Struct(fields) (from {"name": dtype} pairs or a seq of Field). inner, width, shape and fields SHALL read them back, $ SHALL give Polars' names and == SHALL compare the whole type.
let point = Struct({"x": Float64, "y": Float64})
echo List(Int64), " ", Array(Float64, 3), " ", Array(Int64, [2, 3]), " ", point
echo List(point).inner == point, " ", Array(Int64, [2, 3]).shape, " ", point.fields[1].name
list[i64] array[f64, 3] array[i64, (2, 3)] struct[2]
true @[2, 3] y
- WHEN the schema of a frame with a list of strings column is read
- THEN its dtype is
List(String)and$giveslist[str]
- WHEN
fieldsis read from the dtype of a struct column built from(x: 1, y: 2.0) - THEN it holds
x: Int64andy: Float64, in order
Nested columns from Nim
series(name, values) SHALL build a List column from seqs, an Array column from Nim arrays, and a Struct column from objects or named tuples, at any depth (seqs of objects, objects with seq fields). Option values SHALL be null rows, and Option elements null values inside a list. The newDataFrame block and toDataFrame(rows) SHALL take the same values; in the block nil SHALL be a null row. lit(seq) SHALL be a list literal.
let df = newDataFrame:
tags: [@["polar", "bear"], @[], nil]
point: [(x: 1, y: 2.0), (x: 3, y: 4.0), (x: 5, y: 6.0)]
rgb: [[255, 0, 0], [0, 255, 0], [0, 0, 255]]
echo df
echo df.select(lit(@[1, 2]).alias("lit"))
TBD
- WHEN
series("a", newSeq[seq[int]](2))is built - THEN its dtype is
List(Int64)and both values are empty lists
- WHEN
series("a", @[@[some(1), none(int)]])is built - THEN the list holds 1 and null
Nested values to Nim
toList(column, T) SHALL read a List column as seq[U], an Array column as array[N, U] or seq[U], and a Struct column as an object or named tuple matching fields by name, on frames and Series, at any depth; Option[T] SHALL read null rows as none. Cell reads df[column, row, T] and rows(T) SHALL take the same types. A null read into a plain type SHALL raise InvalidOperationError, and an object field without a struct field ColumnNotFoundError.
type Point = object
x: int
y: float
let df = newDataFrame:
tags: [@["polar", "bear"], @[]]
point: [Point(x: 1, y: 2.0), Point(x: 3, y: 4.0)]
echo df.toList("tags", seq[string])
echo df.toList("point", Point)
echo df["point", 1, tuple[x: int]]
for r in df.rows(tuple[tags: seq[string], point: Point]):
echo r.tags.len, " ", r.point.y
@[@["polar", "bear"], @[]]
@[(x: 1, y: 2.0), (x: 3, y: 4.0)]
(x: 3)
2 2.0
0 4.0
- WHEN a seq of objects with seq and object fields is turned into a frame and read back with
rows - THEN the result equals the original seq
- WHEN a list column with a null row is read as
seq[int]rows - THEN
InvalidOperationErroris raised; read asOption[seq[int]]it givesnone
Casting to nested types
cast(dtype) and castTo SHALL accept nested data types, and cast(T) nested Nim types.
let df = newDataFrame(series("a", @[@[1, 2], @[3]]))
echo df.select(col("a").cast(List(Float64)), col("a").cast(seq[string]).alias("s"))
TBD
- WHEN a list column whose lists all have 2 values is cast to
Array(Int64, 2) - THEN the result is an array column
Tasks
1. Implementation
- 1.1Crate: 0.5 Polars features, data type handles, nested Series builders and readers
- 1.2
DataTypeList/Array/Struct,Field, constructors, accessors,$,==,dataType(T) - 1.3
series,newDataFrameblock,toDataFrame,litfor nested values - 1.4
toList, cell reads,rows(T)for nested values; casting to nested types - 1.5Tests in
tests/test_nested.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
5c0aadf 0.5: nested dtypes, list, struct and arr namespaces, nested stringsFirst version: proposal.md, specs/data-types/spec.md, specs/nested-data/spec.md, tasks.md
add-nested-strings Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
Nanuq 0.3 left out the string functions that return lists or structs: str.split alone blocks 12 book sections, extract_all 3, split_exact 2, and json_decode is how JSON in a string column becomes structs. With nested types in place (add-nested-dtypes), they can come in.
It is the third change of the 0.5 release.
What Changes
str.split(by, inclusive)andstr.extractAll(pattern)givelist[str];str.splitExact(by, n, inclusive),str.splitn(by, n)andstr.extractGroups(pattern)give structs (fieldsfield_0, ... or the regex groups).- Matching many literal patterns at once (Aho-Corasick, as in Polars):
str.containsAny(patterns),str.replaceMany(patterns, replaceWith)(also from a mapping{"a": "x"}),str.extractMany(patterns)andstr.findMany(patterns). - JSON in strings:
str.jsonDecode(dtype)(or a Nim type) andstr.jsonPathMatch(path).
Capabilities
Modified Capabilities
strings: string functions that return lists and structs.
Differences from Polars
jsonDecodeneeds the data type, as Polars'Expr.str.json_decodedoes; Python'sSeries.str.json_decodeinfers it, Nanuq does not (there are no Series namespaces).- Patterns are a Nim array of strings, or an expression giving a list.
Impact
src/rust/src/lib.rsandsrc/nanuq/ffi.nim:nq_expr_str_nestedwith an op code.src/nanuq.nim: methods onStrNameSpace.- Tests in
tests/test_strings.nim.
Spec changes
strings modified
Splitting and extracting into lists and structs
str.split(by) SHALL split each string into a list[str] (keeping by with inclusive = true), str.extractAll(pattern) SHALL give all regex matches as a list, str.splitExact(by, n) and str.splitn(by, n) SHALL give a struct of n + 1 or n fields named field_0, ..., and str.extractGroups(pattern) SHALL give a struct with one field per capture group, named after named groups or numbered from 1.
let df = newDataFrame:
station: ["Lima, Peru", "Piura, Peru", "Darwin"]
echo df.select(col("station").str.split(", ").alias("parts"),
col("station").str.splitExact(", ", 1).alias("exact"),
col("station").str.extractGroups(r"(?<city>\w+)(, (?<country>\w+))?").alias("groups"))
TBD
- WHEN
splitExact(", ", 1)is evaluated on a string without a comma - THEN the second field is null
Many patterns at once
str.containsAny(patterns), str.replaceMany(patterns, replaceWith) (or a mapping), str.extractMany(patterns) and str.findMany(patterns) SHALL match many literal patterns in one pass, with asciiCaseInsensitive and, for extract and find, overlapping.
let df = newDataFrame:
note: ["sea ice thin", "no ice", "open water"]
echo df.select(col("note").str.containsAny(["ice", "water"]).alias("any"),
col("note").str.replaceMany({"ice": "ICE", "water": "WATER"}).alias("loud"),
col("note").str.extractMany(["ice", "sea", "water"]).alias("found"))
TBD
- WHEN
replaceMany(["a", "b"], "_")is evaluated on "abc" - THEN the result is "__c"
JSON in strings
str.jsonDecode(dtype) (or jsonDecode(T) with a Nim type) SHALL parse each string as JSON into a value of dtype, and str.jsonPathMatch(path) SHALL give the string at a JSONPath, null when there is none.
let df = newDataFrame:
json: ["""{"bear": "Ada", "kg": 410}""", """{"bear": "Bo", "kg": null}"""]
echo df.select(col("json").str.jsonDecode(tuple[bear: string, kg: Option[int]]).alias("v"),
col("json").str.jsonPathMatch("$.bear").alias("bear"))
TBD
- WHEN a string that is not JSON is decoded
- THEN
ComputeErroris raised
Unchanged in this spec: The str namespace, Matching, Replacing and stripping, Slicing and padding, Joining strings in an aggregation, Building strings from columns, Title case, Escaping and normalizing
Tasks
1. Implementation
- 1.1Crate:
nq_expr_str_nested - 1.2
split,splitExact,splitn,extractAll,extractGroups,containsAny,replaceMany,extractMany,findMany,jsonDecode,jsonPathMatch - 1.3Tests;
nimble testandnimble specexamplespass; CHANGELOG
Revisions
5c0aadf 0.5: nested dtypes, list, struct and arr namespaces, nested stringsFirst version: proposal.md, specs/strings/spec.md, tasks.md
add-nim-callbacks Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
Some work has no Polars expression: a Nim library call, a lookup, a custom parser. Python covers it with user functions (map_elements 7 book sections, fold 7, map_batches 6), and the coverage map lists a Nim callback bridge for 0.5.
It is the seventh change of the 0.5 release.
What Changes
e.mapElements(proc (x: T): U): a typed Nim proc or closure per value. Values are read asT(objects and named tuples for struct rows, seqs for lists), the result type isdataType(U); nulls skip the call unlessTis anOption.e.mapBatches(proc (s: Series): Series), withreturnDtypeandreturnsScalar: the whole column, or each group in a group-by.fold,reduce,cumFold,cumReducewith aproc (acc, x: Series): Series.name.map(proc (name: string): string).groupBy(...).mapGroups(proc (df: DataFrame): DataFrame)on eager frames.- A Nim exception in a callback becomes a
ComputeErrorwith its message. - Series arithmetic broadcasts a Series of length 1 (as
fold's first accumulator is).
Capabilities
New Capabilities
callbacks: Nim functions called by Polars.
Differences from Polars
mapElementsis typed: the argument type says how values are read and the result type givesreturn_dtype, so neither is guessed from the first values as Python does.skip_nullsis the argument type:proc (x: int)skips nulls,proc (x: Option[int])gets them.- Callbacks run one at a time (Polars' worker threads take a lock around Nim code), so they never run in parallel; Python has the GIL for the same reason.
mapGroupsis eager only and runs groups in order of first occurrence.- No
rolling_maporcum_reducewithinclude_init.
Impact
src/rust/src/lib.rsandsrc/nanuq/ffi.nim: C function pointers with a Nim environment (NqUdfFn,NqNameFn,NqDropFn),nq_expr_map_batches,nq_fold,nq_expr_name_map,nq_series_clone,nq_udf_set_error; the crate depends onpolars-planfor function flags.src/nanuq.nim: the callback procs.- New
tests/test_callbacks.nim.
Spec changes
callbacks modified
Typed element callbacks
e.mapElements(f) SHALL call the Nim proc or closure f: proc (x: T): U on each value of e, read as T (as toList reads it: objects and named tuples for structs, seqs for lists), and give a column of dataType(U). Nulls SHALL stay null without a call unless T is an Option. An exception in f SHALL raise ComputeError with its message when the query runs.
type Bear = object
name: string
kg: int
let df = newDataFrame:
name: ["Ada", "Bo", "Cy"]
kg: [410, nil, 500]
let tag = proc (b: Bear): string = b.name & " (" & $b.kg & " kg)"
echo df.select(col("kg").mapElements(proc (x: int): float = x / 1000).alias("t"),
asStruct(col("name"), col("kg").fillNull(0)).mapElements(tag).alias("tag"))
TBD
- WHEN the callback raises
ValueError("no bears") - THEN collecting raises
ComputeErrorwhose message holds "no bears"
Batch callbacks
e.mapBatches(f) SHALL call f: proc (s: Series): Series with the whole column, or in a group-by with each group's values; the result SHALL keep the input type unless returnDtype is given, and with returnsScalar a group-by SHALL get one value per group instead of a list.
let df = newDataFrame:
cubs: [1, 0, 1]
kg: [410, 380, 500]
echo df.select(col("kg").mapBatches(proc (s: Series): Series = s * 2))
echo df.groupBy("cubs").agg(col("kg").mapBatches(proc (s: Series): Series = s.max,
returnsScalar = true)).sort("cubs")
TBD
- WHEN
mapBatches(proc (s: Series): Series = s / 10, Float64)runs on an integer column - THEN the result is a
f64column
Folds
fold(acc, f, exprs) SHALL combine columns left to right with f: proc (acc, x: Series): Series, starting from acc; reduce(f, exprs) SHALL start from the first column, and cumFold and cumReduce SHALL keep each step as a struct field.
let df = newDataFrame:
a: [1, 2]
b: [10, 20]
c: [100, 200]
echo df.select(fold(lit(0), proc (acc, x: Series): Series = acc + x, col("*")).alias("sum"))
TBD
- WHEN
reducewith+runs on columns a and b - THEN the result is 11 and 22
Name and group callbacks
name.map(f) SHALL rename outputs with f: proc (name: string): string, and groupBy(...).mapGroups(f) SHALL call f: proc (df: DataFrame): DataFrame on each group, in order of first occurrence, and concatenate the results.
let df = newDataFrame:
den: ["A", "B", "A"]
kg: [410, 380, 500]
echo df.select(col("*").name.map(proc (n: string): string = n.toUpperAscii))
echo df.groupBy("den").mapGroups(proc (g: DataFrame): DataFrame = g.sort("kg", descending = true).head(1))
TBD
- WHEN
mapGroupsruns on an empty frame - THEN the result is an empty frame with the same columns
Tasks
1. Implementation
- 1.1Crate: Nim function wrapper (lock, errors, drop), map_batches, folds, name.map
- 1.2
mapElements,mapBatches,fold,reduce,cumFold,cumReduce,name.map,mapGroups - 1.3Tests in
tests/test_callbacks.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
f94c8b7 0.5: Nim callbacks and smaller functions (add-nim-callbacks, add-frame-utilities)First version: proposal.md, specs/callbacks/spec.md, tasks.md
add-openspec-page Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 4/4
- Archive
Proposal
Why
specview (tools/specview.nim) is the readable view of the OpenSpec specs and changes, but it only exists as a page attached to PR runs or published by hand as a Claude artifact, so there is no stable link to how Nanuq behaves today. Pietro asked (2026-11-02) for it to be a published page like the Polars coverage map, linked from the README's "How development works" and kept up to date.
What Changes
docs/openspec.nimrendersopenspec.htmlwith the Nanuq theme: the dev log's header and footer, a short introduction to specs and changes, then specview's report (the changes, archived ones behind the checkbox, and every spec in full).tools/specview.nimexposes its report (loadReport,renderNav,renderReport,reportCss,toggleJs) so the page reuses it; the standalone page is unchanged.- CI renders the page in the docs job (with full git history, for revisions) and publishes it at the site root. On
main, pushes that changeopenspec/,BACKLOG.mdortools/specview.nimnow run CI, so the published page follows every merged change. Pull requests touching only those files still skip CI. nimble docsrenders it; the README ("How development works"), the dev-log index and the coverage page link to it.
Capabilities
Modified Capabilities
dev-log: a living OpenSpec page next to the Polars coverage page.ci: render and deploy the living pages; onmain, OpenSpec-only pushes run CI.
Differences from Polars
None: this adds documentation, not API.
Impact
- New
docs/openspec.nim. tools/specview.nim(refactor, no change to its output),.github/workflows/ci.yml,nanuq.nimble,docs/index.nim,docs/polars_coverage.nim,README.md.- An OpenSpec-only merge to
mainnow costs a CI run (the Rust library comes from cache; tests and docs take a few minutes).
Spec changes
ci modified
Skip CI for non-code changes
Tests, example and dev log
Unchanged in this spec: Build Rust only when the crate changes, Lib version follows the crate sources, Fast linking
dev-log modified
OpenSpec page
The site SHALL publish an OpenSpec page at openspec.html, linked from the index, the coverage page and the README's "How development works", rendered by tools/specview.nim with the dev log's header and footer: every change (archived ones hidden until the reader asks for them) and every spec in openspec/specs/ in full. The page is rebuilt from the repository each time the site is, so it shows the specs and changes on main. It is not a dated post and is not listed among the posts.
- WHEN a pull request that archives a change into
openspec/specs/is merged - THEN the published OpenSpec page shows the updated spec and lists the change as archived
- WHEN the site is rendered
- THEN the index links to the OpenSpec page, and the page does not appear in the list of posts
Unchanged in this spec: Index of posts, Dated post files, Polars coverage page, Review mode, Source files
Tasks
1. Implementation
- 1.1Expose specview's report from
tools/specview.nimwithout changing its page - 1.2
docs/openspec.nimrendersopenspec.htmlwith the Nanuq theme - 1.3Render and publish in CI and
nimble docs; run CI onmainfor OpenSpec-only pushes - 1.4Link from the README, the dev-log index and the coverage page
Revisions
5349b11 Publish the OpenSpec page (specview) on the siteFirst version: proposal.md, specs/ci/spec.md, specs/dev-log/spec.md, tasks.md
add-parameter-type-convention Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 1/1
- Archive
Proposal
Why
0.4 introduced four parameter types with converters (ColumnNames, OptInterval, JoinKey, AsofTolerance) so that calls like pivot("season", index = "year") and joinAsof(..., tolerance = 7.days) read like Python. It is a new pattern in the API, and Pietro asked that it be tracked in the API conventions so later changes follow it.
Part of the 0.4 release (#51).
What Changes
- api-conventions gains the rule: parameters that take several types, with a default, use converter types; the four existing types are listed.
- No code change.
Capabilities
Modified Capabilities
api-conventions: the converter parameter type rule.
Differences from Polars
- None in behaviour. Python accepts these unions dynamically; Nanuq accepts the same spellings through converters.
Impact
- Spec only.
Spec changes
api-conventions modified
Parameters that take several types use converter types
Where Python Polars lets a parameter take values of different types (a name or a list of names, a duration string or a number) and the parameter needs a default, Nanuq SHALL use a small exported object type with a converter from each accepted type, instead of a generic union (string | openArray[string] = [] does not compile with a default in Nim) or one overload per combination. The existing types are ColumnNames (a name, a seq or an array of names), OptInterval (a std/times interval or a duration string), JoinKey (a column name or an expression) and AsofTolerance (an interval, a duration string, an int or a float). A new parameter of this kind SHALL reuse one of them when it fits, and a new type SHALL be listed here. Converters SHALL only convert into these types, so they apply only where such a parameter appears.
let df = newDataFrame:
year: [1997, 1997, 1998]
months: ["JJA", "SON", "JJA"]
anomaly: [1.5, 2.3, -0.2]
echo df.pivot("months", index = "year", values = "anomaly").columns
echo df.pivot(["months"], index = @["year"], values = "anomaly").columns
- WHEN user code passes
index = "year"orindex = ["year", "month"]topivot - THEN both compile and mean one or two index columns
- WHEN user code calls
joinAsof(other, on = "t")withouttolerance - THEN it compiles, and no tolerance is applied
Unchanged in this spec: Option values are pure enums with Rust Polars names, The conventions are documented, Python's method parameter is how
Tasks
1. Spec
- 1.1Add the converter parameter type rule to api-conventions, with an example
Revisions
c8c8526 API conventions: converter parameter typesFirst version: proposal.md, specs/api-conventions/spec.md, tasks.md
add-parquet-ipc Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 7/7
- Archive
Proposal
Why
CSV is the only format Nanuq reads and writes. Parquet is what most data arrives in today and what Polars is fastest with; Arrow IPC (Feather v2) is the format other Arrow tools exchange without conversion. Both keep dtypes, which CSV loses: a Date column written to CSV comes back as a string. Reading from a Nim Stream lets a program parse data it already holds in memory (a download, an embedded table, a test fixture) without a temporary file.
This change takes up the BACKLOG.md entry "More IO" (Parquet and IPC) and follows the dev log "Designing Nanuq 0.3", section 5. It is the sixth change of the 0.3 release.
What Changes
- Parquet:
scanParquet(path, nRows, columns, rowIndexName, rowIndexOffset, lowMemory)(a file or glob),readParquet(path or Stream, ...)andwriteParquet(df, path, compression = ParquetCompression.Zstd, compressionLevel = none(int), statistics = true, rowGroupSize = none(int)).ParquetCompressionis a pure enum:Lz4,Uncompressed,Snappy,Gzip,Brotli,Zstd. - IPC:
scanIpc,readIpc(path or Stream, ...)with the same read options, andwriteIpc(df, path, compression = IpcCompression.Uncompressed), withIpcCompressionUncompressed,Lz4,Zstd. - Streams:
readCsv(stream, ...)with every CSV read option. - Hive partitions are detected as in Polars' default for paths; in-memory bytes never are.
- Polars features
parquetandipc(already compiled in by the string change) are used.
Not in this change: writing to a stream or a string, cloud storage, sinkParquet and the other sink functions (streaming writes), Parquet useStatistics, parallel and hive options, readParquetSchema, IPC streams (readIpcStream), NDJSON and Excel.
Capabilities
New Capabilities
parquet-ipc: reading and writing Parquet and Arrow IPC files and bytes.
Modified Capabilities
csv-io: reading CSV from a stream.native-bridge:NqParquetCompressionandNqIpcCompressionjoin the ordered enums;nq_lf_scan_csvtakes optional in-memory bytes.
Differences from Polars
Expected differences from Polars' Rust and Python APIs:
- Streams: Python reads any file-like object or
bytes; Rust uses readers overCursors. Nanuq reads a NimStream, all of it, whenreadCsv/readParquet/readIpcis called. Thescan*procs take paths only. - Compression is a pure enum instead of Python's strings (
"zstd") and Rust's enum with the level inside (Zstd(Some(ZstdLevel))); the level is a separatecompressionLevel, as in Python. A level with a codec that has none raisesValueError(Python ignores it). statisticsis a bool (Python also takes"full"or a dict).IpcCompressionhasUncompressedas a value (Python's"uncompressed"; Rust usesNone).- Names follow Polars in camelCase:
row_index_name→rowIndexName,compression_level→compressionLevel,row_group_size→rowGroupSize.
Impact
src/rust/src/lib.rs:nq_lf_scan_parquet,nq_lf_scan_ipc,nq_df_write_parquet,nq_df_write_ipc, the two compression enums, and bytes fornq_lf_scan_csv.src/nanuq/ffi.nim,src/nanuq.nim: the declarations and procs;nanuqimportsstd/streams.tests/test_io.nim(new); README; BACKLOG "More IO" keeps the remaining formats.
Spec changes
csv-io modified
Reading CSV from a stream
readCsv SHALL also take a Nim Stream instead of a path, read all of it when called, and take every CSV read option.
import std/streams
let text = "station;bears\nNorth;3\nSouth;NA\n"
echo readCsv(newStringStream(text), separator = ';', nullValues = ["NA"])
TBD
- WHEN CSV text with
;separators and "NA" is read from a stream withseparator = ';', nullValues = ["NA"] - THEN the result equals reading the same text from a file with those options
- WHEN an empty stream is read
- THEN
NoDataErroris raised
Unchanged in this spec: Scanning CSV, CSV read options, CSV write options, Quoting, encoding and new column names, Comment lines
native-bridge modified
Nim declarations mirror the C ABI
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release
parquet-ipc modified
Reading Parquet
The API SHALL provide scanParquet(path, ...), a lazy scan of a file or a glob, and readParquet(path, ...), which is scanParquet(...).collect. Both SHALL take nRows, columns, rowIndexName with rowIndexOffset = 0, and lowMemory = false. Every dtype Nanuq models SHALL round-trip through Parquet unchanged.
let path = getTempDir() / "riders.parquet"
let df = newDataFrame:
rider: ["Seixas", "Pogačar", "Evenepoel"]
born: [date(2006, 9, 24), date(1998, 9, 21), date(2000, 1, 25)]
wins: [3, 22, nil]
df.writeParquet(path)
echo readParquet(path, columns = ["rider", "born"], nRows = 2, rowIndexName = "nr")
TBD
- WHEN a DataFrame with string, date and nullable integer columns is written and read back
- THEN the result equals the original, dtypes included
- WHEN bytes that are not Parquet are read
- THEN
PolarsErroris raised
Writing Parquet
writeParquet(df, path, compression = ParquetCompression.Zstd, compressionLevel = none(int), statistics = true, rowGroupSize = none(int)) SHALL write a Parquet file. compressionLevel SHALL apply to Gzip, Brotli and Zstd; with another codec it SHALL raise ValueError, and an out-of-range level SHALL raise PolarsError.
import std/sequtils
let path = getTempDir() / "sizes.parquet"
let df = newDataFrame(series("n", toSeq(1..1000)))
for c in [ParquetCompression.Uncompressed, ParquetCompression.Zstd]:
df.writeParquet(path, compression = c)
echo c, " ", getFileSize(path) < 5000
TBD
- WHEN a DataFrame is written with each
ParquetCompressionvalue - THEN each file reads back with the same rows
- WHEN
writeParquet(path, compression = ParquetCompression.Snappy, compressionLevel = 3)is called - THEN
ValueErroris raised
- WHEN the target directory does not exist
- THEN
IOErroris raised
Arrow IPC
The API SHALL provide scanIpc and readIpc with the read options of Parquet, and writeIpc(df, path, compression = IpcCompression.Uncompressed) with Lz4 and Zstd.
let path = getTempDir() / "riders.arrow"
let df = newDataFrame:
rider: ["Seixas", "Pogačar"]
start: [timeOfDay(13, 10), timeOfDay(13, 12)]
df.writeIpc(path, compression = IpcCompression.Lz4)
echo readIpc(path).schema
TBD
- WHEN a DataFrame is written with each
IpcCompressionand read back - THEN the result equals the original
Reading from streams
readParquet and readIpc SHALL also take a Nim Stream instead of a path, read all of it when called, and take the same options.
import std/streams
let path = getTempDir() / "one.parquet"
newDataFrame(series("a", [1, 2])).writeParquet(path)
echo readParquet(newStringStream(readFile(path))).shape
TBD
- WHEN the bytes of a Parquet file are read with
readParquet(newStringStream(bytes)) - THEN the result equals reading the file
Unchanged in this spec: Hive partitioning switch, Arrow IPC streams
Design
Design
One scan per format, paths or bytes
Every reader goes through a lazy scan in Rust, which takes either a path (file or glob) or a byte buffer (ScanSources::Buffers). Eager read* procs are scan*(...).collect, and the Stream overloads read the stream into a string and pass its bytes, which Rust copies. One code path per format keeps the options identical for files and streams.
Columns are a projection
columns becomes a select after the scan, as in scanCsv; Polars pushes it down into the reader, so unread columns are never decoded.
Hive partitions
Polars' Rust default enables hive partitioning, Python's detects it (None). Nanuq uses Python's behaviour for paths. Polars does not implement hive partitioning for in-memory buffers, so it is disabled there.
Tasks
1. Bridge
- 1.1Add
nq_lf_scan_parquet,nq_lf_scan_ipc,nq_df_write_parquetandnq_df_write_ipcwith the compression enums - 1.2Let
nq_lf_scan_csvread in-memory bytes; mirror everything inffi.nim
2. Nim API
- 2.1Add
ParquetCompression,IpcCompression,scanParquet,readParquet,writeParquet,scanIpc,readIpcandwriteIpc - 2.2Add the
Streamoverloads ofreadCsv,readParquetandreadIpc - 2.3Write
tests/test_io.nim; add it tonanuq.nimbleand.gitignore
3. Docs and integration
- 3.1README lists the formats;
nimble testandnimble specexamplespass - 3.2Archive the change: update BACKLOG "More IO", add CHANGELOG lines
Revisions
f846b99 Add Parquet and Arrow IPC IO, and reading from streamsFirst version: design.md, proposal.md, specs/csv-io/spec.md, specs/native-bridge/spec.md, specs/parquet-ipc/spec.md, tasks.md
add-plan-serialization Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
A serialized query plan can be stored, sent to another process or machine and run there; Python Polars uses it for Polars Cloud and for caching plans. The roadmap lists plan serialization and the rest of the meta namespace in 0.6 ("Engine and edges"). 0.5 added only meta.outputName, rootNames, hasMultipleOutputs, isColumn and isLiteral.
It is the second change of the 0.6 release.
What Changes
SerializationFormatenum (Binary,Json).lf.serialize(format = Binary): stringandlf.serialize(path, format);deserialize(LazyFrame, data, format)anddeserializeFile(LazyFrame, path, format). The plan keeps in-memory frames, so a serialized eager frame's query carries its data.e.meta.serialize(format)anddeserialize(Expr, data, format).- More of
meta:eq,ne,pop,isRegexProjection,isColumnSelection(allowAliasing),isLiteral(allowAliasing),treeFormat.
Capabilities
New Capabilities
plan-serialization: serializing LazyFrames and expressions.
Differences from Polars
- Binary data is returned as a Nim
stringof bytes (Pythonbytes), and a file is written by an overload taking a path (Python'sfileargument). - Python's classmethods
pl.LazyFrame.deserialize(source)andpl.Expr.deserializebecomedeserialize(LazyFrame, data)anddeserialize(Expr, data); reading a file isdeserializeFile. - Plans contain Nim callbacks (
mapElements,mapBatches, ...) as function pointers, which cannot be serialized: serializing them raisesComputeError(Python pickles the Python function). - Plans written by Nanuq (Rust Polars 0.55.2) and by py-polars are only compatible when their plan format version (
DSL_VERSION) matches. - No
DataFrame.serialize; usewriteIpc/writeParquet, ordf.lazy.serialize. treeFormatreturns the text; there is noreturn_as_string = falseprinting mode.
Impact
src/rust/Cargo.toml: Polars featuresserde,serde-lazy;serde_jsonandpolars-utils(for Polars' binary expression format).src/rust/src/lib.rs,src/nanuq/ffi.nim:nq_lf_serialize,nq_lf_deserialize,nq_expr_serialize,nq_expr_deserialize, moremetaoperations.- New
tests/test_serialization.nim.
Spec changes
plan-serialization modified
Serializing query plans
lf.serialize(format = SerializationFormat.Binary) SHALL return the LazyFrame's plan as bytes (in a string), Json as JSON text, and lf.serialize(path, format) SHALL write it to a file. deserialize(LazyFrame, data, format) and deserializeFile(LazyFrame, path, format) SHALL rebuild a LazyFrame that collects to the same result. In-memory frames in the plan SHALL travel with it.
let lf = newDataFrame(series("kg", @[410, 380, 455])).lazy.filter(col("kg") > 400)
let bytes = lf.serialize
echo deserialize(LazyFrame, bytes).collect
echo lf.serialize(SerializationFormat.Json).len > 0
TBD
- WHEN
deserialize(LazyFrame, "garbage")is called - THEN
PolarsErroris raised
- WHEN a plan with
mapElementsis serialized - THEN
PolarsErroris raised
Serializing expressions
e.meta.serialize(format) SHALL return an expression as bytes or JSON, and deserialize(Expr, data, format) SHALL rebuild it.
let e = (col("kg") * 2).alias("double")
let back = deserialize(Expr, e.meta.serialize)
echo back.meta.eq(e)
echo newDataFrame(series("kg", @[1, 2])).select(back)
TBD
- WHEN an expression is serialized with
Jsonand deserialized withJson - THEN
meta.eqwith the original is true
Expression metadata
The meta namespace SHALL also provide eq(other) and ne(other) (same expression tree), pop (the inputs of the outermost node), isRegexProjection, isColumnSelection(allowAliasing = false), isLiteral(allowAliasing) and treeFormat (the tree as text).
let e = (col("a") + col("b")).alias("c")
echo e.meta.undoAliases.meta.outputName
echo e.meta.pop.len
echo col("^x.*$").meta.isRegexProjection, " ", col("a").alias("b").meta.isColumnSelection(allowAliasing = true)
echo (col("a") + 1).meta.treeFormat
TBD
- WHEN
col("a").meta.eq(col("b"))is called - THEN it is false
Tasks
1. Implementation
- 1.1Crate: features serde/serde-lazy; plan and expression (de)serialization; meta operations
- 1.2
SerializationFormat,serialize,deserialize,deserializeFile,meta.* - 1.3Tests in
tests/test_serialization.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
4ea5dad 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6First version: proposal.md, specs/plan-serialization/spec.md, tasks.md
add-polars-coverage-page Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
The Polars coverage map (every Polars feature group, and whether Nanuq has it) was made on 2026-10-28 as a planning artifact outside the repo, and it went stale after four releases. Pietro asked (2026-11-01) for it to be a separate document that gets updated, not a dev-log post, and chose a page on the Nanuq site built from a data file in the repo.
What Changes
docs/coverage/polars.json: the catalogue for the latest release, 128 feature groups in 14 areas, each with the Polars names, a status (has it, partly, missing, not planned), a note on what is still missing, a priority for open groups and a mark on the groups new in that release. Older releases are not kept (Pietro, 2026-11-02); once the next release has a plan, rows can name the release that plans them.docs/polars_coverage.nim: renders it topolars_coverage.htmlwith the Nanuq theme: release totals, a table by area, the groups still open by priority, and the catalogue, with the dev log's header and footer. It does not import Nanuq.- The dev-log index links to the page; CI and
nimble docsrender it and publish it at the site root. - Each release PR refreshes the data (the release, the changed rows and their new-marks).
Capabilities
Modified Capabilities
dev-log: a living Polars coverage page next to the dated posts.
Differences from Polars
None: this adds documentation, not API. The page uses Polars' Python names and says that Nanuq spells them in camelCase.
Impact
- New
docs/coverage/polars.json,docs/polars_coverage.nim. docs/index.nim(link),.github/workflows/ci.ymlandnanuq.nimble(render and publish the page).
Spec changes
dev-log modified
Polars coverage page
The site SHALL publish a Polars coverage page at polars_coverage.html, linked from the index and the README, rendered from the data file docs/coverage/polars.json. The page SHALL describe the latest Nanuq release only: the data names that release and lists Polars feature groups by area with their Polars names, a status (has it, partly, missing, not planned), a note naming what is still missing, a priority for open groups, and a mark on the groups whose status changed in that release. When the next release has a plan, the data MAY name it and mark the open groups it plans; the page SHALL then show them. The page SHALL show the release totals, counts by area, the open groups by priority and the full catalogue, with the dev log's header and footer. Each release PR SHALL refresh the data for that release. The page is not a dated post and is not listed among the posts.
- WHEN the 0.7 release PR sets the release to 0.7, clears the old new-marks, and updates and marks the rows that 0.7 changed
- THEN the page shows only 0.7 statuses, with the changed groups marked as new in 0.7
- WHEN the data names no next release
- THEN the page shows no Planned column
- WHEN the site is rendered
- THEN the index links to the coverage page, and the page does not appear in the list of posts
Unchanged in this spec: Index of posts, Dated post files, OpenSpec page, Review mode, Source files
Tasks
1. Implementation
- 1.1Catalogue data in
docs/coverage/polars.json, statuses for 0.5 (main) and 0.6 (#59) - 1.2
docs/polars_coverage.nimrenders the page with the Nanuq theme - 1.3Link from the dev-log index; render and publish in CI and
nimble docs
Revisions
0d00929 Add the Polars coverage map as a page on the Nanuq siteFirst version: proposal.md, specs/dev-log/spec.md, tasks.md
6ede49a Coverage page: latest release only (0.6), no per-version historyproposal.mdspecs/dev-log/spec.mdadd-repeat-by-and-seeds Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
The 0.5 book port of the O'Reilly chapter 8 examples found two more small gaps: Expr.repeatBy was missing, and sample(n, seed = 42) needed seed = some(42) on expressions and lists (frames and shuffle already took a plain int).
It is the eleventh change of the 0.5 release (#53).
What Changes
Expr.repeatBy(by), withbya count, a column name or an expression: each value repeated as a list.sample(..., seed = 42)with a plain int on Expr and onlist.
Capabilities
Modified Capabilities
list-functions: repeating values into lists; seeds as plain ints.
Differences from Polars
- None in behaviour. Python's
seed=Noneis Nanuq's default; a seed is given as an int.
Impact
- Rust:
nq_expr_repeat_by. src/nanuq.nim:repeatBy,sampleoverloads withseed: int.
Spec changes
list-functions modified
Repeating values into lists
Expr.repeatBy(by) SHALL repeat each value by times into a list, where by is an int, a column name or an expression (Python's repeat_by).
let df = newDataFrame:
hut: ["Goûter", "Margherita"]
nights: [2, 1]
echo df.select(col.hut.repeatBy("nights"))
- WHEN
repeatBy(2)runs on "x" - THEN the result is the list
["x", "x"]
Seeds as plain ints
sample on expressions and on list SHALL take the seed as a plain int, sample(3, seed = 42), as shuffle and frame sample do; the same seed SHALL give the same values.
let df = newDataFrame:
m: [4806, 4634, 4061, 4506, 4478]
echo df.select(col.m.sample(3, seed = 42)).height
- WHEN
sample(3, seed = 42)runs twice on the same column - THEN both runs give the same values
Unchanged in this spec: List aggregations and access, List transforms, Expressions on list elements, Explode and implode, Exploding several columns by name
Tasks
1. Implementation
- 1.1
nq_expr_repeat_byandExpr.repeatBy - 1.2
sample(seed: int)overloads on Expr andlist - 1.3Tests
Revisions
d8f7ab7 0.5: repeatBy, int seeds, mapElements benchmark and fast pathFirst version: proposal.md, specs/list-functions/spec.md, tasks.md
add-reshaping Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 4/4
- Archive
Proposal
Why
Data arrives wide or long, and analysis wants the other shape: NOAA publishes its El Niño index as one row per year with twelve season columns, a spreadsheet keeps one column per month, and a report wants the stations as columns. Nanuq can't reshape at all: pivot was dropped from 0.3, and the book ports stop on unpivot, pivot and transpose (O'Reilly chapters 4, 9 and 17, the user guide's "Pivots" and "Unpivots" pages), and on partition_by (O'Reilly chapter 1, "Load").
It is the sixth change of the 0.4 release.
What Changes
pivoton DataFrame (finds the new columns itself, in order of appearance or sorted withsortColumns) and on LazyFrame (with the new columns given inonColumns), withindex,values,aggregateFunction(aPivotAggpure enum or an expression onelement()),maintainOrderandseparator.unpivoton DataFrame and LazyFrame, withon,index,variableNameandvalueName.transposewithincludeHeader,headerNameandcolumnNames.partitionByreturning aseq[DataFrame], withmaintainOrderandincludeKey.toDummieswithcolumns,separator,dropFirstanddropNulls.ColumnNames, a parameter type that takes one name or a list (index = "year"orindex = ["year", "month"]),element()andExpr.item(allowEmpty).
Capabilities
New Capabilities
reshaping: pivot, unpivot, transpose, partitionBy, toDummies.
Differences from Polars
aggregateFunctionis thePivotAggpure enum (Item,First,Last,Sum,Mean,Median,Min,Max,Len) or an expression; Python takes strings or an expression and None, which Nanuq spellsItem(the default, at most one value per cell).index,valuesandontake names (one or a list), not selectors.partitionByhas noas_dict; the frames come in aseqin order of appearance.column_namingis always Polars' "auto".
Impact
src/rust/src/lib.rs:nq_lf_pivot,nq_lf_unpivot,nq_df_transpose,nq_df_partition_by,nq_df_array_free,nq_df_to_dummies,nq_expr_element,nq_expr_item;src/nanuq/ffi.nim,src/nanuq.nim.- New
tests/test_reshaping.nim.
Spec changes
reshaping modified
Pivot
df.pivot(on, index, values, aggregateFunction = PivotAgg.Item, maintainOrder = true, sortColumns = false, separator = "_") SHALL turn each distinct value of the on columns into a column (in order of appearance, or sorted), with one row per distinct index value and cells from values combined by aggregateFunction, a PivotAgg or an expression on element(). When index or values is left out it SHALL mean every other column. lf.pivot(on, onColumns, ...) SHALL do the same lazily with the new columns listed in the DataFrame onColumns.
let df = newDataFrame:
year: [2023, 2023, 2024, 2024]
season: ["DJF", "JJA", "DJF", "JJA"]
oni: [-0.7, 1.1, 1.8, 0.0]
echo df.pivot("season", index = "year", values = "oni")
TBD
- WHEN two rows share an index and an
onvalue andaggregateFunction = Sum - THEN their cell holds the sum of both values
- WHEN two rows share an index and an
onvalue and no aggregation is given - THEN
pivotraises aPolarsError
Unpivot
unpivot(on, index, variableName = "variable", valueName = "value") on a DataFrame or LazyFrame SHALL turn the on columns (by default every column not in index) into rows, one per index value and on column, holding the column's name and value.
let df = newDataFrame:
year: [2023, 2024]
DJF: [-0.7, 1.8]
JJA: [1.1, 0.0]
echo df.unpivot(index = "year", variableName = "season", valueName = "oni")
TBD
- WHEN a long frame is pivoted and the result unpivoted on the new columns
- THEN the rows are the original rows
Transpose
df.transpose(includeHeader = false, headerName = "column", columnNames) SHALL turn rows into columns, naming them columnNames or column_0, column_1, ..., and with includeHeader SHALL put the old column names in a first column headerName.
let df = newDataFrame:
lima: [22.1, 24.3]
quito: [14.0, 14.2]
echo df.transpose(includeHeader = true, headerName = "station", columnNames = ["jan", "feb"])
TBD
- WHEN a frame with two rows is transposed without names
- THEN its columns are column_0 and column_1
Partition
df.partitionBy(by, maintainOrder = true, includeKey = true) SHALL return one DataFrame per distinct value of the by columns, in order of appearance with maintainOrder, and without the by columns when includeKey is false.
let df = newDataFrame:
phase: ["El Niño", "La Niña", "El Niño"]
year: [2015, 2020, 2023]
for part in df.partitionBy("phase", includeKey = false):
echo part.toList("year", int)
TBD
- WHEN
partitionBy(["a", "b"])runs on rows with three distinct (a, b) pairs - THEN the result has three frames
Dummy columns
df.toDummies(columns, separator = "_", dropFirst = false, dropNulls = false) SHALL replace each listed column (all by default) by one 0/1 column per distinct value, named column, separator and value.
let df = newDataFrame:
phase: ["warm", "cold", "warm"]
echo df.toDummies()
TBD
- WHEN
toDummies(dropFirst = true)runs on a column with values a and b - THEN only one dummy column remains
Tasks
1. Implementation
- 1.1
ColumnNames,element(),Expr.item - 1.2
pivoton DataFrame and LazyFrame withPivotAgg - 1.3
unpivot,transpose,partitionBy,toDummies - 1.4Tests in
tests/test_reshaping.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
570d956 Nanuq 0.4, changes 1-7: math, cumulative, rolling, value functions, horizontal, reshaping, time groupingFirst version: proposal.md, specs/reshaping/spec.md, tasks.md
add-review-mode Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 6/6
- Archive
Proposal
Why
Pietro reviews the dev-log posts and explainers from his phone, and so far every remark went into a chat message that had to say where on the page it was. tabelline, his other nimib project, has a review mode for its pages (docs/review.nim, not yet in nimib): a reader opens it with ✎ Review, selects text, comments on it, and exports every comment as one text (Markdown with a YAML block naming the page, its source and the version read) that a coding agent applies to the page's source. Pietro asked (2026-11-19) for it on every nimib page of Nanuq, nanuq-more and the Nanuq book.
He also asked for tabelline's folded code (nbFoldCode): the posts name source files (ffi.nim, benchmarks/arrow_views.nim, an explainer's Python twin) that a reader can only find on GitHub. tabelline folds each piece of code a page talks about under its name and its length, in a section the page points to.
What Changes
docs/review.nimanddocs/review.js: tabelline's review mode, copied as they are (the version with review rounds, tabelline#102), without tabelline's notebook-look styles. They are meant to move to nimib; until then this copy follows tabelline's.useNanuqThemeturns the review mode on for every page that uses the theme (all posts, the index, the coverage map, the OpenSpec page, and nanuq-more's pages, which use the same theme), withreview = falseto leave it off. The version line (Version 8 · updated 2 Nov 2026) and ✎ Review sit in the masthead under the meta line; the review mode's colours come from the pack-ice palette, light and dark.docs/foldcode.nim:nbFoldCode(a file, or a part of it betweenstartandstop, folded under its path or a title and its length) andnbSourceFiles, a "Source files" section at the end of a page. The theme says under the title that the section is there, links every file name the text shows as code (ffi.nim,src/nanuq/ffi.nim) to its fold, and a link to a fold opens it. Every post that mentions a file of this repository gets the section; the explainers' links to their Python twins, figures and data scripts on GitHub now lead to their folds. Files of other repositories stay links.- The version of a page is the number of commits that touched its source, read from git when the page is built; the docs job already checks out the whole history.
Capabilities
Modified Capabilities
dev-log: every page of the site has the review mode; pages that mention source files fold them in a "Source files" section.
Differences from Polars
None: this changes the documentation site, not the API.
Impact
- New
docs/review.nim,docs/review.js,docs/foldcode.nim;docs/nanuqtheme.nim; the eleven pages that mention source files (ten posts and the OpenSpec page). - Each page carries the review script inline (about 30 KB), so a page stays one file and works as a Claude artifact too.
- Comments live in the reader's browser (localStorage), keyed by page and version.
Spec changes
dev-log modified
Review mode
Every page rendered with the Nanuq theme SHALL have the review mode of docs/review.nim (from tabelline, until nimib has it), unless the page passes review = false: a version line in the masthead (Version N · updated D, N being the commits that touched the page's source) with ✎ Review, which opens a mode where the reader selects text, comments on it, and exports the comments as Markdown with a YAML block (nimib-review format) naming the page, its source, its version and commit. The page SHALL stay readable at phone width in both modes, light and dark.
- WHEN a reader opens a post on a phone, taps ✎ Review, selects a sentence and writes a note
- THEN the sentence is marked, the note is kept in the browser, and Export gives a text
- naming the post's source (
docs/blog/<post>.nim), its version and the quoted sentence
- WHEN a commit changes a post's source and the site is built again
- THEN the post's version goes up by one, and its comments start empty
Source files
A page that mentions source files of the repository SHALL fold them (whole, or the part it discusses) in a "Source files" section at its end, made with nbSourceFiles and nbFoldCode (from tabelline): each under its path or a title, with its number of lines. The top of the page SHALL point to the section, every file name shown as code in the text SHALL link to its fold, and following such a link SHALL open the fold.
- WHEN a reader taps
ffi.nimin the text of a post - THEN the page goes to the fold of
src/nanuq/ffi.nimin "Source files", opened
Unchanged in this spec: Index of posts, Dated post files, Polars coverage page, OpenSpec page
Tasks
Tasks
- Copy tabelline's review mode (rounds version) to
docs/review.nimanddocs/review.js - Turn it on in
useNanuqTheme, with the version line in the masthead and the palette's colours - Check a post at phone width: reading, selecting, commenting, exporting
- Port
nbFoldCodetodocs/foldcode.nim, withnbSourceFiles, mention links and folds that open - Add a Source files section to every page that mentions a source file of the repository
- Sync the
dev-logspec and add the CHANGELOG line
Revisions
37224c5 Review mode and folded source files on every page of the siteFirst version: proposal.md, specs/dev-log/spec.md, tasks.md
add-rolling-and-ewm Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 5/5
- Archive
Proposal
Why
Smoothing a noisy series is the first thing done with any measurement over time: a 7-day average of cases, a 30-year climate normal, NOAA's El Niño index (a 3-month running mean of sea temperature anomalies). Nanuq has none of Polars' rolling or exponentially weighted functions, and no way to fill a gap from its neighbours (interpolate, which the O'Reilly chapter on missing values uses three times).
It is the third change of the 0.4 release.
What Changes
- Fixed windows:
rollingSum,rollingMean,rollingMin,rollingMax,rollingMedian,rollingStd,rollingVarandrollingQuantile, withwindowSize,weights,minSamplesandcenter. - Time windows: the same functions with a
Bysuffix (rollingMeanBy(by, 7.days)), over a sorted temporal or integer column, withminSamplesandclosed(ClosedWindow). Window sizes are std/times intervals or Polars duration strings, as in 0.3'sdateRange. - Exponentially weighted:
ewmMean,ewmStd,ewmVarwith exactly one ofcom,span,halfLife,alpha, plusadjust,bias,minSamples,ignoreNulls. - Interpolation:
interpolate(InterpolationMethod.Linear | Nearest)andinterpolateBy(by).
Capabilities
New Capabilities
rolling-windows: fixed and time-based rolling windows, exponentially weighted functions.
Modified Capabilities
missing-values: interpolation.
Differences from Polars
- The decay parameters of
ewmMeandefault to NaN, meaning "not given", and must be named (ewmMean(span = 12)); Python uses None. Rust takes onlyalpha; Nanuq convertscom,spanandhalfLifethe way Python does. minSamplesfollows Python 2's name (Rust:min_periods).- The
Byvariants takebyas a column name or expression, and Nim intervals as well as Polars duration strings. - Not included:
rollingMap(needs Nim callbacks, 0.5),rollingSkew,rollingKurtosis,rollingRank,ewmMeanBy, and Python'srolling_*on frames (that is the rolling group-by in add-dynamic-group-by).
Impact
src/rust/src/lib.rs:nq_expr_rolling,nq_expr_rolling_by,nq_expr_ewm,nq_expr_interpolate,NqBinaryFn.InterpolateBy;src/nanuq/ffi.nim,src/nanuq.nim.- New
tests/test_rolling.nim.
Spec changes
missing-values modified
Interpolation
e.interpolate() SHALL fill nulls that lie between two values on a straight line between them, or with the nearest value for interpolate(InterpolationMethod.Nearest); e.interpolateBy(by) SHALL interpolate linearly using the distances in column by. Nulls before the first and after the last value SHALL stay null.
let df = newDataFrame:
day: [1, 2, 4, 5]
temp: [10.0, nil, 16.0, nil]
echo df.withColumns(col.temp.interpolate.alias("linear"),
col.temp.interpolateBy("day").alias("by_day"))
TBD
- WHEN
interpolateruns on 1, null, 3 - THEN the result is 1.0, 2.0, 3.0
Unchanged in this spec: Nulls are read as Option, Plain reads refuse nulls, Inspecting nulls, Building columns with nulls, CSV null markers, Null expressions, Dropping rows with nulls, Null literal, Filling nulls in whole frames
rolling-windows modified
Fixed rolling windows
rollingSum, rollingMean, rollingMin, rollingMax, rollingMedian, rollingStd, rollingVar and rollingQuantile SHALL compute their statistic over the last windowSize rows, or over a window centred on each row with center = true. A row SHALL get null until minSamples non-null values are in its window (by default windowSize), and weights, when given, SHALL multiply the values of each window.
let df = newDataFrame:
season: ["NDJ", "DJF", "JFM", "FMA", "MAM"]
anomaly: [1.9, 2.1, 1.6, 1.0, 0.4]
echo df.withColumns(col.anomaly.rollingMean(3).round(2).alias("mean3"),
col.anomaly.rollingMean(3, center = true).round(2).alias("centred"),
col.anomaly.rollingMax(2, minSamples = 1).alias("max2"))
TBD
- WHEN
rollingSum(3)runs on 1, 2, 3, 4 - THEN the result is null, null, 6, 9
- WHEN
rollingSum(2, weights = [0.5, 1.0])runs on 2.0, 4.0 - THEN the second value is 5.0
- WHEN
rollingMean(0)is built - THEN
ValueErroris raised
Time rolling windows
The same functions with a By suffix SHALL take a sorted column by (temporal or integer) and a window size as a std/times interval or Polars duration string; the window of each row SHALL span windowSize back from its by value, with ends included as closed (ClosedWindow, default Right) says, and rows SHALL need minSamples values (default 1).
let df = newDataFrame:
day: [date(2026, 7, 1), date(2026, 7, 2), date(2026, 7, 5), date(2026, 7, 6)]
rain: [4, 0, 10, 2]
echo df.withColumns(col.rain.rollingSumBy("day", 3.days).alias("last_3_days"))
TBD
- WHEN
rollingSumBy("day", 3.days)runs on July 1, 2, 5, 6 with 4, 0, 10, 2 - THEN the result is 4, 4, 10, 12
Exponentially weighted functions
ewmMean, ewmStd and ewmVar SHALL compute exponentially weighted statistics with the decay given by exactly one of com, span, halfLife or alpha, converted to alpha as Python Polars does, and SHALL take adjust, minSamples and ignoreNulls (and bias for std and var). Giving none or more than one decay parameter SHALL raise ValueError.
let df = newDataFrame:
temp: [14.0, 15.0, 13.0, 16.0]
echo df.withColumns(col.temp.ewmMean(alpha = 0.5).round(3).alias("ewm"),
col.temp.ewmMean(span = 3, adjust = false).round(3).alias("span3"))
TBD
- WHEN
ewmMean(span = 3)andewmMean(alpha = 0.5)run on the same column - THEN the results are equal
- WHEN
ewmMean(com = 1, alpha = 0.5)is built - THEN
ValueErroris raised
Tasks
1. Implementation
- 1.1Fixed-window rolling functions with weights, minSamples, center
- 1.2Time-window
Byvariants with closed windows - 1.3
ewmMean,ewmStd,ewmVarwith Python's alpha conversion - 1.4
interpolate,interpolateBy - 1.5Tests in
tests/test_rolling.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
570d956 Nanuq 0.4, changes 1-7: math, cumulative, rolling, value functions, horizontal, reshaping, time groupingFirst version: proposal.md, specs/missing-values/spec.md, specs/rolling-windows/spec.md, tasks.md
add-row-objects Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
Nim code works with typed records. Getting rows out of a frame into objects (to feed a template, a plotting call or a simulation), or building a frame from a seq of objects, takes one toList or series call per column today. Python has df.rows(named=True), iter_rows and pl.DataFrame(list_of_dicts); the Datamancer gap analysis lists "row objects" as something Datamancer users expect, and the coverage map puts it in 0.4.
It is the tenth change of the 0.4 release.
What Changes
df.rows(T)returns aseq[T]anddf.iterRows(T)iterates, for T an object or named tuple whose fields name columns;df.row(i, T)returns one row.toDataFrame(seq[T])builds a frame with one column per field.- Field types: int, float, bool, string, temporal values (
Date,DateTime, ...), Nim enums, andOptionof these for columns with nulls.
Capabilities
New Capabilities
row-objects: rows as typed Nim objects and back.
Differences from Polars
- The row type is a Nim type chosen by the caller; Python returns tuples or dicts.
- Fields match columns by exact name (no style-insensitive matching), and columns without a field are ignored.
iterRowsreads whole columns first; Python'siter_rowsbuffers rows in chunks.
Impact
src/nanuq.nim:rows,iterRows,row,toDataFrame. No ABI change.- New
tests/test_rows.nim.
Spec changes
row-objects modified
Rows as objects
df.rows(T) SHALL return the rows as a seq[T] and df.iterRows(T) SHALL iterate them, for T an object or named tuple whose fields are named after columns, and df.row(i, T) SHALL return row i (negative from the end). Fields SHALL be int, float, bool, string, temporal values, Nim enums, or Option of these; a null read into a plain field SHALL raise InvalidOperationError, and a field without a column ColumnNotFoundError.
type Reading = object
station: string
rain: float
let df = newDataFrame:
station: ["Lima", "Piura", "Tumbes"]
rain: [1.5, 80.0, 95.0]
year: [1998, 1998, 1998]
for r in df.iterRows(Reading):
echo r.station, ": ", r.rain
echo df.row(-1, tuple[station: string, year: int])
TBD
- WHEN
rowsis called with a type that has a fieldwindand the frame has no columnwind - THEN
ColumnNotFoundErroris raised
Objects to a frame
toDataFrame(rows) SHALL build a frame from a seq or array of objects or named tuples, with one column per field in field order; Option fields SHALL give columns with nulls.
type Event = object
year: int
peak: Option[float]
let events = @[Event(year: 1997, peak: some(2.4)), Event(year: 2014, peak: none(float))]
echo events.toDataFrame
TBD
- WHEN a seq of objects is turned into a frame and read back with
rows - THEN the result equals the original seq
Tasks
1. Implementation
- 1.1
rows,iterRows,rowfor objects and named tuples - 1.2
toDataFramefrom a seq of objects - 1.3Tests in
tests/test_rows.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
46ae6c2 Nanuq 0.4, changes 8-10: Series API, Arraymancer tensors, row objectsFirst version: proposal.md, specs/row-objects/spec.md, tasks.md
add-sample-datasets Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 5/5
- Archive
Proposal
Why
Examples, tests and docs need small, well-known data that loads with one call and no path. Today they read examples/iris_sample.csv, a 12-row iris sample found by relative path. Pietro wants penguins (palmerpenguins, CC0) instead of iris. Penguins is also a better showcase now that Nanuq supports nulls: it has missing values in five columns.
This takes up the BACKLOG.md entry "Sample datasets" (Datasets), including its sub-item "Replace iris with penguins".
What Changes
- New module
nanuq/datasetswithpenguins(): DataFrame, the full palmerpenguins table (344 rows, 8 columns, "NA" read as null). It callsreadCsvon the CSV that ships next to the module, with the path fixed at compile time (currentSourcePath), so it works from any working directory and needs no network and no change to the Rust bridge. This is a convenience while Nanuq is young; the datasets are expected to move out later. - The README example,
examples/basic.nimand the CSV tests use penguins instead of iris. (During implementation Pietro asked to switch the two dev-log posts to penguins too and removeexamples/iris_sample.csv.)
Capabilities
New Capabilities
datasets: bundled sample datasets, how they are loaded, and their licensing.
Modified Capabilities
None.
Differences from Polars
- Bundled datasets. Neither Polars (Rust or Python) nor pandas ship datasets. This follows the plotting libraries instead: seaborn's
load_dataset("penguins")downloads and caches, Plotly Express bundles its data (px.data.iris()), and R bundles it in packages (palmerpenguins::penguins). Bundling in Nanuq is a convenience for early development, not a design choice. Once the library matures, the datasets will probably be dropped and vendored from elsewhere (see the backlog). - Same table as seaborn and R. Columns and values match palmerpenguins'
penguins.csv(the R package's data). Seaborn's copy has the same 344 rows but noyearcolumn and sex spelledMALE/FEMALE; Nanuq keeps the R version. - Not embedded. Embedding the CSV with
staticReadwould make binaries self-contained, but needs a read-CSV-from-string function in the bridge. Since the datasets are temporary,penguins()reads the file instead: a compiled program needs the Nanuq sources on disk where it was built. Reading CSV from memory (Python'spl.read_csv(io.StringIO(...))) stays in the backlog.
Impact
- No change to
rust/src/lib.rsorffi.nim, so CI needs no Rust rebuild. src/nanuq/datasets.nimandsrc/nanuq/data/penguins.csv(with a credit and CC0 notice insrc/nanuq/data/README.md). The data lives undersrc/so it ships with the package.README.md,examples/basic.nim,tests/: switch to penguins.
Spec changes
datasets modified
Purpose: Small, well-known datasets loadable with one call and no file path, for examples, tests and documentation. They are bundled for convenience during early development and are expected to move out of the library later.
Penguins dataset
nanuq/datasets SHALL provide penguins() returning the palmerpenguins table: 344 rows and the columns species, island, bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g, sex and year, with "NA" fields as nulls.
- WHEN
penguins()is called - THEN the result has shape (344, 8) and the columns listed above, in that order
- WHEN
penguins()is called - THEN
nullCountis 2 for body_mass_g and 11 for sex, and body_mass_g is an integer column
Loading from any working directory
Bundled datasets SHALL load with no path from the caller and without using the network, whatever the program's working directory.
- WHEN a compiled program calls
penguins()from any working directory - THEN the dataset loads
Licensing
Every bundled dataset SHALL ship with its source, credit and license in the repository, and SHALL be under a license that allows redistribution.
- WHEN someone looks for where penguins comes from
- THEN the data folder names palmerpenguins, its authors and CC0
Tasks
1. Datasets module
- 1.1Add
src/nanuq/data/penguins.csv(palmerpenguinsinst/extdata/penguins.csv) andsrc/nanuq/data/README.mdwith source, authors and CC0; verify the file has 345 lines - 1.2Add
src/nanuq/datasets.nimwithpenguins()callingreadCsvoncurrentSourcePath.parentDir / "data" / "penguins.csv"withnullValues = ["NA"]; verify with tests for shape, column order, null counts and dtypes, run from a different working directory
2. Penguins instead of iris
- 2.1Rewrite the README example and its output, and
examples/basic.nim, with penguins (e.g. mean body mass and count per species, afterdropNulls); verifynimble exampleprints what the README shows - 2.2Switch the CSV read test in
tests/test_basic.nimto penguins or the fixture, and update thesrc/nanuq.nimmodule doc example; verifynimble testpasses - 2.3Check CI is green on the PR
Workflow follow-up
Revisions
5a0c831 Archive add-sample-datasets: backlog to changelogFirst version: .openspec.yaml, proposal.md, specs/datasets/spec.md, tasks.md
ad5de5a Switch dev-log posts to penguins, drop iris sample, link posts in READMEproposal.mdadd-series-api Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 4/4
- Archive
Proposal
Why
Polars users reach for a single column all the time: df["oni"].max(), (s - s.mean()) / s.std(), s.value_counts(). In Nanuq a Series is only a way to build a frame; there is no way to get one back, so every question about one column needs select and toList. The coverage map put "a real Series" at the head of 0.4, and the user guide's "Series" snippets and Packt's chapter 1 lean on it.
Polars itself is moving towards expressions everywhere, and Series methods in py-polars are mostly thin wrappers that evaluate an expression. Nanuq can do the same: a Series method runs the expression of the same name on a one-column frame. This adds the whole Series surface with almost no new ABI.
It is the eighth change of the 0.4 release.
What Changes
- Getting a Series:
df["name"],df.getColumn("name"),df.toSeries(index). - Inspecting it:
name,len,dtype,nullCount,$(Polars' Series display),toList(T),s[i, T],item(T),toFrame,alias/rename,cast,describe,valueCounts. - Operating on it: arithmetic and comparison operators with literals and other Series,
filter(mask), and every expression method that takes no other column (aggregations, math, cumulative, rolling, ranking, distinct values, recoding, binning:s.rollingMean(3),s.cut([0.0])), each evaluated through the expression of the same name.eval(s, expr)runs any expression on a Series. - Back into frames:
df.withColumns(series)andlit(series)in expressions.
Capabilities
New Capabilities
series: getting, inspecting and operating on single columns.
Differences from Polars
- Aggregations return a Series of one value (
s.sum), read withitem(T)(s.sum.item(float)); Python returns a Python scalar. Nim needs the type at compile time, and keeping a Series lets aggregations chain. - A Series does not convert to an expression automatically: use
lit(s)(Python accepts a Series wherever an expression goes). - Series methods that would take other columns (
sortBy,topKBy,interpolateBy,over) are not forwarded; use a frame. - No in-place methods (
append,extend,set,scatter): Nanuq values are immutable.
Impact
src/rust/src/lib.rs:nq_df_get_column,nq_df_to_series,nq_series_to_frame,nq_series_name,nq_series_len,nq_series_rename,nq_series_to_string;src/nanuq/ffi.nim;src/nanuq.nim(the forwarding macro).- New
tests/test_series.nim.
Spec changes
series modified
Getting a Series
df["name"] and df.getColumn("name") SHALL return the column as a Series, and df.toSeries(index = 0) the column at a position (negative from the end); a missing column SHALL raise ColumnNotFoundError. A Series SHALL have name, len, dtype, nullCount and $, which shows Polars' Series display.
let df = newDataFrame:
year: [1997, 2015, 2023]
oni: [2.4, 2.6, 2.0]
let s = df["oni"]
echo s
echo s.name, " ", s.len, " ", s.dtype
TBD
- WHEN
df["nope"]runs on a frame without that column - THEN
ColumnNotFoundErroris raised
Reading a Series
s.toList(T) and s.toList(Option[T]) SHALL return the values, s[i, T] one value, and s.item(T) the only value of a one-value Series (raising InvalidOperationError otherwise). toFrame SHALL return a one-column frame, and alias/rename and cast SHALL return a renamed or converted Series.
let s = series("oni", [2.4, 2.6, 2.0])
echo s.toList(float), " ", s[1, float]
echo s.toFrame.columns
TBD
- WHEN
item(float)is called on a Series of three values - THEN
InvalidOperationErroris raised
Series operations
Series SHALL support the arithmetic, comparison and boolean operators with literals and other Series of the same length, filter(mask), and the expression methods that take no other column (aggregations, math, cumulative, rolling, ranking, distinct values, recoding, binning), each SHALL give the same values as the expression of the same name on a one-column frame. Aggregations SHALL return a Series of one value.
let s = series("oni", [0.5, -1.0, 2.0, 1.2])
echo s.max.item(float)
echo ((s - s.mean.item(float)) / s.std.item(float)).round(2).toList(float)
echo s.filter(s > 0.5).toList(float)
echo s.rollingMean(2).toList(Option[float])
TBD
- WHEN
a + bruns on Series a = 1, 2 and b = 10, 20 - THEN the result is 11, 22 named like
a
Series in frames
df.withColumns(series...) SHALL add or replace columns with Series of the frame's height, and lit(series) SHALL use a Series as a column in an expression.
let df = newDataFrame:
year: [1997, 2015, 2023]
let peak = series("peak", [2.4, 2.6, 2.0])
echo df.withColumns(peak, (peak * 10).alias("tenths"))
TBD
- WHEN
select(col.year + lit(series("d", [1, 1, 1])))runs - THEN each year grows by one
Unchanged in this spec: Series namespaces, Series as HTML, Columns from sized numbers, Binary functions on a Series
Tasks
1. Implementation
- 1.1Getting a Series from a frame; name, len, dtype, display, reads
- 1.2Operators,
filter,eval, forwarded expression methods - 1.3
withColumns(series),lit(series),valueCounts,describe - 1.4Tests in
tests/test_series.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
46ae6c2 Nanuq 0.4, changes 8-10: Series API, Arraymancer tensors, row objectsFirst version: proposal.md, specs/series/spec.md, tasks.md
add-spec-examples Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 7/7
- Archive
Proposal
Why
Scenarios state the rules precisely, but they are hard to read: a WHEN/THEN sentence describes a call and its result in prose, and the reader has to picture both. A short piece of Nim and the table it prints shows the same thing at a glance, the way Polars' own docs do.
Examples that nobody runs go stale, so they must be checked, like tests.
This change comes from a request in the project thread (no BACKLOG.md entry).
What Changes
- Every requirement that describes Nim API gets an example: a
nim` block right after the requirement text and before the scenarios, followed by a
Capabilities
New Capabilities
spec-examples: runnable examples in the OpenSpec specs, their format, and the checker.
Modified Capabilities
ci: main specs trigger CI again, and CI runs the spec examples.
Impact
openspec/specs/*/spec.md(examples only, no requirement text changes)tools/specexamples.nim(new),tools/specview.nim,nanuq.nimble.github/workflows/ci.yml,openspec/config.yaml- The specs grow by about 70%, mostly output tables.
Differences from Polars
None: this change adds no Nim API. The examples follow Polars' docs in showing code with the printed table under it.
Spec changes
ci modified
Skip CI for non-code changes
Tests, example and dev log
Unchanged in this spec: Build Rust only when the crate changes, Lib version follows the crate sources, Fast linking
spec-examples modified
API requirements have examples
Every requirement in openspec/specs/ that describes Nim API SHALL include an example: a
allowed use; failures stay in scenarios. Requirements about process (CI, releases, the dev log, the C ABI) need none.
let df = newDataFrame(series("a", [1, 2, 3]))
echo df.select(col("a").isIn([1, 3]))
shape: (3, 1)
┌───────┐
│ a │
│ --- │
│ bool │
╞═══════╡
│ true │
│ false │
│ true │
└───────┘
- WHEN a change adds or modifies a requirement that describes Nim API
- THEN its delta includes the example and the expected output
- WHEN a requirement describes CI or the release process
- THEN it has no example
Examples are run
nimble specexamples SHALL compile and run every nim block in openspec/specs/, with nanuq, nanuq/datasets and std/[options, os, strutils] imported, and fail when an example does not compile, fails at run time, or prints something other than its text block. With --update it SHALL write the actual output into the text blocks instead. Change deltas SHALL NOT be run.
nimble specexamples # check every spec
nim r tools/specexamples.nim --update expressions # refresh one spec's outputs
- WHEN a behavior change makes an example print a different table
- THEN
nimble specexamplesfails and shows the expected and actual output
- WHEN it runs with
--update - THEN the text blocks hold the actual output and the run passes
- WHEN an open change's delta has an example using API that does not exist yet
- THEN the checker ignores it
specview shows examples
specview SHALL keep fenced code in a requirement verbatim, never reading a line inside a fence as a heading, and SHALL render text ` blocks as output, set apart from the code.
- WHEN an example has a line starting with
#or## - THEN specview shows it in the code block, and the requirement and its scenarios are unchanged
Design
Design
Where examples go
Inside each requirement, after the SHALL text and before the first scenario. Tested with the OpenSpec CLI (1.16):
openspec validatepasses, and fences are parsed as code: a### Requirement:line inside a fence does not start a requirement.- The code does not count towards the "requirement text too long" warning.
- Archive keeps fenced blocks in ADDED and MODIFIED requirements, so a change that alters behavior restates and updates the example in its delta, and specview shows that diff.
A spec-level ## Examples section also validates and survives archive, but deltas can never change it, so it would drift. Rejected.
Format
let df = newDataFrame(series("a", [1, 2, 3])) echo df.select(col("a").isIn([1, 3]))
shape: (3, 1) ...
nanuq,nanuq/datasetsandstd/[options, os, strutils]are imported implicitly; an example's ownimportlines (e.g.nanuq/datamancer) are hoisted.- Each example is self-contained: tiny frames built inline, or
penguins(). Files go ingetTempDir(). echoa frame when the shape or dtypes matter;echotoSeq,columnsorshapewhen only values do. Full Polars tables are kept (decided by Pietro).- A
nim` block with no text block after it is compiled and run, but its output is not compared.
The checker
tools/specexamples.nim builds one program per spec: each example inside a block:, preceded by an echo of a marker, so one compile covers a spec and the output splits back per example. The 46 examples take about 90 seconds locally. Extra -d: flags are passed to the compile (CI uses -d:nanuqNoCargo). --update writes the actual output into the text blocks; the diff is then reviewed like any other change.
Only openspec/specs/ is checked. A proposal's examples describe future API, so they cannot run; their outputs are written by hand and corrected with --update when the change is implemented and archived.
CI trigger
paths-ignore cannot re-include a path, and **.md matches every spec. ci.yml switches to paths with negated patterns, where the last matching pattern wins: "**", then "!**.md", "!openspec/**", ..., then "openspec/specs/**". The Rust library is cached, so a spec-only change costs a test run.
Tasks
1. Checker
- 1.1Add
tools/specexamples.nim(run, compare,--update, capability filter, pass-through-d:flags) and thenimble specexamplestask - 1.2Make
tools/specview.nimfence-aware when parsing specs, and styletext` blocks as output
2. Examples
- 2.1Add an example to every API requirement of the 11 API specs and fill outputs with
--update - 2.2Review every output against the requirement and its scenarios
3. CI and conventions
- 3.1Switch
ci.ymltopathswith negations soopenspec/specs/**triggers CI, and runnimble specexamplesin the test job - 3.2Add the example rule for spec deltas to
openspec/config.yaml - 3.3Archive the change; add a CHANGELOG line
Revisions
6c9d2a0 Implement add-spec-examplesFirst version: .openspec.yaml, design.md, proposal.md, specs/ci/spec.md, specs/spec-examples/spec.md, tasks.md
add-specview-full-specs Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
specview shows OpenSpec changes, but not the specs they produce: to read what the API promises today, Pietro has to open each openspec/specs/*/spec.md on GitHub. And with every change archived, the page is dominated by finished work. Pietro asked on 2026-11-01 for the full specs in the viewer and for archived changes to be hidden by default.
What Changes
- specview renders every main spec in full (purpose, requirements with their examples and scenarios), one collapsible block per capability, with an index. Specs touched by an open change, or changed since
--base, are marked. - Archived changes are hidden by default, in the overview and in the page, behind a "Show archived changes" checkbox (remembered in the browser). Archived changes that changed since
--basestay visible, so a PR that archives changes still shows them. A link to a hidden change reveals it. - A small navigation bar links to Changes, Specs and (with
--base) the file diff.
Capabilities
New Capabilities
spec-review: what the specview page shows.
Differences from Polars
None: this is repository tooling, with no API surface.
Impact
tools/specview.nimonly (still standard library only).
Spec changes
spec-review modified
Full specs in specview
specview SHALL render every spec in openspec/specs/ in full, with its purpose, requirements, examples and scenarios, and SHALL mark the specs that an open change modifies or that changed since --base.
- WHEN a reviewer opens the Specs section and expands
temporal - THEN every requirement of
openspec/specs/temporal/spec.mdis shown with its example and scenarios
Archived changes are hidden by default
specview SHALL hide archived changes until the reader ticks "Show archived changes", except archived changes that changed since --base. A link to a hidden change SHALL reveal it.
- WHEN specview runs without
--baseon a repository whose changes are all archived - THEN no change is shown until the checkbox is ticked
- WHEN specview runs with
--base:origin/mainon a branch that archived three changes - THEN those three changes are shown and the other archived ones are hidden
Tasks
Tasks
- 1.1Render every main spec with an index and open-change markers
- 1.2Hide archived changes behind a checkbox, except those changed since
--base - 1.3Navigation bar; check the page in a browser with and without
--base
Revisions
b5d2d7e specview: show every spec in full, hide archived changes by defaultFirst version: proposal.md, specs/spec-review/spec.md, tasks.md
add-sql Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
SQL is the most used API still missing from the book ports: SQLContext.execute appears in 18 sections and SQLContext in 10, mostly the user guide's SQL chapters. For users coming from SQL it is also the shortest way in. The coverage map lists it as one bridge call behind the sql feature.
It is the sixth change of the 0.5 release.
What Changes
SQLContext:newSQLContext()ornewSQLContext({"bears": lf}),register(LazyFrame or DataFrame),unregister,tables, andexecute(query)giving a LazyFrame (or a DataFrame witheager = true).sqlContext(bears, dens), a macro that registers frames under their variable names (what Python'sregister_globalsand keyword arguments do).lf.sql(query, tableName = "self")anddf.sql(...), andsql(query, frames).- SQL table functions (
read_csv,read_parquet,read_ipc,read_json) work in queries.
Capabilities
New Capabilities
sql: running SQL queries on frames.
Differences from Polars
- No
register_globals(Nim cannot list a scope's variables at run time); thesqlContext(a, b)macro names frames after the variables passed to it instead. executereturns a LazyFrame unlesseager = true, as in Python;df.sqlreturns a DataFrame,lf.sqla LazyFrame.- No
register_manywith a dict:newSQLContextandregistertake{"name": frame}.
Impact
src/rust/src/lib.rsandsrc/nanuq/ffi.nim:nq_sql_*functions on an opaque context.src/nanuq.nim:SQLContextand helpers.- New
tests/test_sql.nim.
Spec changes
sql modified
SQL contexts
newSQLContext() SHALL make an empty context and newSQLContext({"name": frame}) one with frames registered; register(name, frame) SHALL add a LazyFrame or DataFrame, unregister(name) remove it and tables list the names in sorted order; execute(query) SHALL run a SQL query on the registered frames and give a LazyFrame, or a DataFrame with eager = true.
let bears = newDataFrame:
bear: ["Ada", "Bo", "Cy"]
kg: [410, 380, 500]
let ctx = newSQLContext({"bears": bears.lazy})
echo ctx.tables
echo ctx.execute("SELECT bear, kg FROM bears WHERE kg > 400 ORDER BY kg DESC", eager = true)
TBD
- WHEN a query reads a table that is not registered
- THEN
SqlErroris raised
Frames by variable name
sqlContext(a, b, ...) SHALL make a context with each frame registered under the name of the variable passed.
let bears = newDataFrame:
bear: ["Ada", "Bo"]
den: [1, 2]
let dens = newDataFrame:
den: [1, 2]
site: ["Kong Karls Land", "Hopen"]
let ctx = sqlContext(bears, dens)
echo ctx.execute("SELECT bear, site FROM bears JOIN dens USING (den)").collect
TBD
- WHEN
sqlContext(bears.lazy)is compiled - THEN compilation fails with a message asking for a variable
SQL on a frame
df.sql(query) and lf.sql(query) SHALL run a query on the frame, which the query calls self (or tableName), and sql(query, {"name": frame}) SHALL run a query on the given frames.
let df = newDataFrame:
island: ["Biscoe", "Dream", "Biscoe"]
kg: [4.5, 3.7, 5.1]
echo df.sql("SELECT island, AVG(kg) AS kg FROM self GROUP BY island ORDER BY island")
TBD
- WHEN
df.sql("SELECT * FROM penguins", tableName = "penguins")is run - THEN the result is the frame
Tasks
1. Implementation
- 1.1Crate: SQL context new/free/register/unregister/tables/execute
- 1.2
SQLContext,newSQLContext,sqlContextmacro,sqlon frames and as a function - 1.3Tests in
tests/test_sql.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
1b5c5b7 0.5: SQL contexts and queries (add-sql)First version: proposal.md, specs/sql/spec.md, tasks.md
add-streaming-and-sinks Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
Polars' streaming engine runs a query in batches, so it can process data larger than memory, and sinks write a query's result straight to files without collecting it first. The coverage roadmap puts both first in 0.6 ("Engine and edges"), the 0.6 book map needs sink_csv (Packt ch2) and the user guide's streaming page, and BACKLOG.md "More IO" names sink functions. The crate already compiles the streaming engine (the json feature pulls it in), so this is a thin layer.
It is the first change of the 0.6 release. It takes the "sink functions" part of the BACKLOG.md entry "More IO".
What Changes
Engineenum (Auto,InMemory,Streaming) andcollect(lf, engine),collectAll(lfs, engine).sinkParquet,sinkIpc,sinkCsv,sinkNdjsonon LazyFrames, with the options of the matchingwrite*procs plusmaintainOrderandmkdir. They run the query with the streaming engine and write the file; withlazy = truethey return the sink plan as a LazyFrame instead, to run later withcollector several at once withcollectAll.PartitionBy(basePath, key, includeKey, maxRowsPerFile)as the target of a sink writes one file per key value (Hive-style directories) or per row count.profile(lf)returns the result and a frame of node timings.
Capabilities
New Capabilities
streaming: the streaming engine, sinks and query profiling.
Differences from Polars
Enginehas noGpu(Python only, through cuDF).lazyis astatic bool:sinkParquet(path)returns nothing,sinkParquet(path, lazy = true)returns a LazyFrame (Python returnsNoneor a LazyFrame from the same call).- No cloud targets (
storage_options,credential_provider,retries), nosync_on_close, no Parquetmetadataorfield_overwrites, nooptimizationsargument.PartitionByhas nofile_pathcallback and noapproximate_bytes_per_file. - Python's
profilecan also show a plot; Nanuq returns the two frames.
Impact
src/rust/src/lib.rs,src/nanuq/ffi.nim:nq_lf_collect_engine,nq_lf_sink,nq_lf_profile, engine argument onnq_collect_all.src/nanuq.nim: the procs above.- New
tests/test_streaming.nim.
Spec changes
streaming modified
Choosing the engine
collect(lf, engine) SHALL run the query with the given Engine: Auto (Polars picks, today the in-memory engine), InMemory or Streaming, which processes the data in batches. Every engine SHALL give the same rows; collectAll(lfs, engine) SHALL take the same choice.
let lf = newDataFrame(series("kg", @[410, 380, 455])).lazy
echo lf.filter(col("kg") > 400).collect(engine = Engine.Streaming)
TBD
- WHEN a group-by query is collected with
Engine.InMemoryand withEngine.Streaming - THEN both frames are equal after sorting
Sinks
sinkParquet, sinkIpc, sinkCsv and sinkNdjson SHALL run a LazyFrame with the streaming engine and write the result to a file, with the options of writeParquet, writeIpc, writeCsv and writeNdjson, plus maintainOrder = true and mkdir = false (create missing directories). With lazy = true they SHALL return the sink as a LazyFrame, which writes the file when collected; collectAll SHALL run several such sinks together.
let dir = getTempDir() / "nanuq-sinks"
let lf = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380])).lazy
lf.sinkCsv(dir / "bears.csv", mkdir = true)
echo readFile(dir / "bears.csv")
let sinks = [lf.sinkParquet(dir / "bears.parquet", lazy = true),
lf.filter(col("kg") > 400).sinkNdjson(dir / "big.ndjson", lazy = true)]
discard collectAll(sinks)
echo readParquet(dir / "bears.parquet").height, " ", readFile(dir / "big.ndjson")
TBD
- WHEN a sink targets a directory that does not exist and
mkdiris false - THEN
IOErroris raised and no file is written
Partitioned sinks
A sink SHALL accept a PartitionBy(basePath, key, includeKey = true, maxRowsPerFile) target instead of a path: with key it SHALL write one Hive-style directory per key value (basePath/key=value/...), without it files of at most maxRowsPerFile rows.
let base = getTempDir() / "nanuq-by-year"
let df = newDataFrame(series("year", @[2024, 2024, 2025]), series("n", @[1, 2, 3]))
df.lazy.sinkParquet(PartitionBy(basePath: base, key: @["year"]), mkdir = true)
echo scanParquet(base / "**/*.parquet").sort("n").collect
TBD
- WHEN 10 rows are sunk with
PartitionBy(basePath: dir, maxRowsPerFile: 4) - THEN reading every file in
dirgives the 10 rows back
Profiling
profile(lf) SHALL run the query and return a tuple of the result and a frame with one row per executed node (node, start, end, in microseconds).
let (res, timings) = newDataFrame(series("x", @[1, 2, 3])).lazy.select(col("x").sum).profile
echo res
echo timings.columns
TBD
- WHEN a query is profiled
- THEN every
endis at least itsstart
Tasks
1. Implementation
- 1.1Crate: collect with engine, sinks (file and partitioned), profile, engine for collect_all
- 1.2
Engine,collect(engine),collectAll(engine),sink*,PartitionBy,profile - 1.3Tests in
tests/test_streaming.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
4ea5dad 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6First version: proposal.md, specs/streaming/spec.md, tasks.md
add-string-expressions Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 7/7
- Archive
Proposal
Why
Real tables arrive with messy strings: en dashes in race names ("Paris–Nice"), times written as "73h 56′ 26″", riders whose names need upper-casing or trimming. Nanuq 0.2 has no string functions at all, so none of that can be cleaned inside a query. The 0.3 explainer needs replaceAll, extract, an aggregation that joins a rider's races into one string, and format to print cycling-style gaps.
This change takes up the BACKLOG.md entry "More expressions" (string functions). It is the fourth change of the 0.3 release, following the dev log "Designing Nanuq 0.3", section 4 (the str namespace as a distinct Expr, Rust regex, literal = true) and the later additions confirmed by Pietro on 2026-10-31 (format, str.join).
What Changes
e.strreturns aStrNameSpace(adistinct Expr) with Polars' string functions, in camelCase:lenChars,lenBytes,toUppercase,toLowercase,reverse;stripChars,stripCharsStart,stripCharsEnd(whitespace, or the given characters),stripPrefix,stripSuffix;startsWith,endsWith,contains(pattern, literal = false, strict = true),find,countMatches,extract(pattern, groupIndex = 1);replace(pattern, value, literal = false, n = 1),replaceAll(pattern, value, literal = false);slice(offset, length),head(n),tail(n),padStart(length, fillChar = ' '),padEnd,zfill;join(delimiter = "", ignoreNulls = true), an aggregation. Patterns, lengths and offsets take a Nim value or an expression.concatStr(exprs, separator = "", ignoreNulls = false)andformat("{} ({})", col.rider, col.nat), as Polars'concat_strandformat.- Polars features
strings,regex,string_pad,string_reverse, andconcat_strare compiled in.
Not in this change: split, extractAll, extractGroups, splitExact (they return List or Struct columns), toTitlecase (needs Polars' nightly feature), strptime, toDate, toDatetime and toTime (the temporal change), toInteger (needs Polars' 128-bit integer dtypes; cast(int) parses decimal strings), normalize, json*, encode/decode, containsAny/replaceMany.
Capabilities
New Capabilities
strings: thestrnamespace,concatStrandformat.
Modified Capabilities
native-bridge:NqStrOpjoins the enums kept in the same order.
Differences from Polars
Expected differences from Polars' Rust and Python APIs:
- Regex syntax is Rust's
regexcrate, as in both Polars APIs: no backreferences, no lookaround. literal,strict,n,groupIndexare named arguments as in Python. Rust'scontains_literal/find_literalandreplace_nbecome theliteralandnarguments.stripChars()without characters strips whitespace, as Python'sstrip_chars(None); Rust takes a null literal.formatchecks the number of placeholders against the arguments when the expression is built, as Python does; it is Nanuq's own proc, built onconcatStr. It overloadsstrutils.format, which takes strings, not expressions.- Names follow Polars in camelCase:
len_chars→lenChars,strip_chars_start→stripCharsStart,concat_str→concatStr.
Impact
src/rust/src/lib.rs:nq_expr_str(one entry point withNqStrOp) andnq_expr_concat_str; five Polars features inCargo.toml.src/nanuq/ffi.nim,src/nanuq.nim: the declarations,StrNameSpaceand its procs,concatStr,format.tests/test_strings.nim(new); README; BACKLOG "More expressions" is removed.
Spec changes
native-bridge modified
Nim declarations mirror the C ABI
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release
strings modified
The str namespace
e.str SHALL give access to string functions that return expressions: lenChars, lenBytes, toUppercase, toLowercase and reverse. Nulls SHALL stay null in every string function, unless stated otherwise.
let df = newDataFrame:
rider: ["Pogačar", "Seixas", nil]
echo df.select(col.rider, col.rider.str.toUppercase.alias("upper"),
col.rider.str.lenChars.alias("chars"), col.rider.str.lenBytes.alias("bytes"))
shape: (3, 4)
┌─────────┬─────────┬───────┬───────┐
│ rider ┆ upper ┆ chars ┆ bytes │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ u32 ┆ u32 │
╞═════════╪═════════╪═══════╪═══════╡
│ Pogačar ┆ POGAČAR ┆ 7 ┆ 8 │
│ Seixas ┆ SEIXAS ┆ 6 ┆ 6 │
│ null ┆ null ┆ null ┆ null │
└─────────┴─────────┴───────┴───────┘
- WHEN
str.lenCharsandstr.lenBytesrun over "Pogačar" - THEN the results are 7 and 8
- WHEN
str.toUppercaseruns over an i64 column - THEN
PolarsErroris raised when the query runs
Matching
The namespace SHALL provide startsWith(prefix), endsWith(suffix), contains(pattern, literal = false, strict = true), find(pattern, literal = false, strict = true), countMatches(pattern, literal = false) and extract(pattern, groupIndex = 1). Patterns SHALL be Rust regular expressions unless literal = true. With strict = false, an invalid regex SHALL give null instead of raising.
let df = newDataFrame:
race: ["Paris–Nice", "Milano-Sanremo", "Tour de France"]
echo df.select(col.race,
col.race.str.contains("–", literal = true).alias("en_dash"),
col.race.str.startsWith("Tour").alias("tour"),
col.race.str.extract(r"^(\w+)", 1).alias("first"),
col.race.str.countMatches("[aeiou]").alias("vowels"))
shape: (3, 5)
┌────────────────┬─────────┬───────┬────────┬────────┐
│ race ┆ en_dash ┆ tour ┆ first ┆ vowels │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ bool ┆ bool ┆ str ┆ u32 │
╞════════════════╪═════════╪═══════╪════════╪════════╡
│ Paris–Nice ┆ true ┆ false ┆ Paris ┆ 4 │
│ Milano-Sanremo ┆ false ┆ false ┆ Milano ┆ 6 │
│ Tour de France ┆ false ┆ true ┆ Tour ┆ 5 │
└────────────────┴─────────┴───────┴────────┴────────┘
- WHEN
str.contains(".")andstr.contains(".", literal = true)run over "abc" - THEN the results are true and false
- WHEN
str.extract(r"(\d+)'")runs over "73h" - THEN the result is null
- WHEN
str.contains("(")runs, and thenstr.contains("(", strict = false) - THEN the first raises
PolarsErrorand the second gives null
Replacing and stripping
The namespace SHALL provide replace(pattern, value, literal = false, n = 1), replaceAll(pattern, value, literal = false), stripChars, stripCharsStart and stripCharsEnd (whitespace without an argument, otherwise the given characters), stripPrefix(prefix) and stripSuffix(suffix). In a regex replacement, $1 SHALL refer to a capture group.
let df = newDataFrame:
race: [" Paris–Nice ", "Tirreno–Adriatico", "Strade Bianche"]
echo df.select(col.race.str.stripChars.str.replaceAll("–", "-", literal = true).alias("clean"),
col.race.str.replace(r"(\w+) (\w+)", "$2 $1").alias("swapped"))
shape: (3, 2)
┌───────────────────┬───────────────────┐
│ clean ┆ swapped │
│ --- ┆ --- │
│ str ┆ str │
╞═══════════════════╪═══════════════════╡
│ Paris-Nice ┆ Paris–Nice │
│ Tirreno-Adriatico ┆ Tirreno–Adriatico │
│ Strade Bianche ┆ Bianche Strade │
└───────────────────┴───────────────────┘
- WHEN
str.replace("a", "o", n = 2)runs over "banana" - THEN the result is "bonona"
- WHEN
str.stripChars("*")runs over "win" - THEN the result is "win"
Slicing and padding
The namespace SHALL provide slice(offset) and slice(offset, length) (a negative offset counts from the end), head(n), tail(n), padStart(length, fillChar = ' '), padEnd(length, fillChar = ' ') and zfill(length), counting characters.
let df = newDataFrame:
bib: ["1", "21", "141"]
nat: ["SLO", "FRA", "DEN"]
echo df.select(col.bib.str.zfill(3).alias("bib"), col.bib.str.padStart(4, '.').alias("dots"),
col.nat.str.head(2).alias("head"), col.nat.str.slice(-2).alias("last2"))
shape: (3, 4)
┌─────┬──────┬──────┬───────┐
│ bib ┆ dots ┆ head ┆ last2 │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str │
╞═════╪══════╪══════╪═══════╡
│ 001 ┆ ...1 ┆ SL ┆ LO │
│ 021 ┆ ..21 ┆ FR ┆ RA │
│ 141 ┆ .141 ┆ DE ┆ EN │
└─────┴──────┴──────┴───────┘
- WHEN
str.slice(1, 2)runs over "Pogačar" - THEN the result is "og"
Joining strings in an aggregation
str.join(delimiter = "", ignoreNulls = true) SHALL aggregate a column into one string, in row order, per group in agg. With ignoreNulls = false, a null SHALL make the result null.
let wins = newDataFrame:
rider: ["Pogačar", "Seixas", "Pogačar"]
race: ["Strade Bianche", "Flèche Wallonne", "Il Lombardia"]
echo wins.groupBy(col.rider).agg(col.race.str.join(", ").alias("races")).sort("rider").collect
shape: (2, 2)
┌─────────┬────────────────────────────────┐
│ rider ┆ races │
│ --- ┆ --- │
│ str ┆ str │
╞═════════╪════════════════════════════════╡
│ Pogačar ┆ Strade Bianche, Il Lombardia │
│ Seixas ┆ Flèche Wallonne │
└─────────┴────────────────────────────────┘
- WHEN
select(col.race.str.join("|"))runs over "a", null, "b" - THEN the result is one row holding "a|b"
Building strings from columns
concatStr(exprs, separator = "", ignoreNulls = false) SHALL concatenate expressions row by row into a string column, and format(template, args...) SHALL replace each {} in template by the next argument. Non-string arguments SHALL be formatted as Polars casts them to strings. A null argument SHALL make the row null, unless ignoreNulls = true in concatStr. A template whose placeholders don't match the number of arguments SHALL raise ValueError.
let gaps = newDataFrame:
rider: ["Vingegaard", "Pogačar"]
minutes: [4, 0]
seconds: [23, 7]
echo gaps.select(format("{}: {}′ {}″", col.rider, col.minutes, col.seconds).alias("gap"),
concatStr([col.rider, lit("UAE")], separator = " / ").alias("team"))
shape: (2, 2)
┌────────────────────┬──────────────────┐
│ gap ┆ team │
│ --- ┆ --- │
│ str ┆ str │
╞════════════════════╪══════════════════╡
│ Vingegaard: 4′ 23″ ┆ Vingegaard / UAE │
│ Pogačar: 0′ 7″ ┆ Pogačar / UAE │
└────────────────────┴──────────────────┘
- WHEN
format("{} {}", col.a)is called - THEN
ValueErroris raised
- WHEN a module imports
std/strutilsandnanuqand callsformat("{}", col.a)and"$1".format("x") - THEN both compile, the first giving an expression and the second "x"
Unchanged in this spec: Title case, Splitting and extracting into lists and structs, Many patterns at once, JSON in strings, Escaping and normalizing
Design
Design
Decisions
One ABI function for the namespace
Polars' string functions differ only in which arguments they take: up to two expressions (pattern and value, offset and length), up to two booleans (literal, strict), a count, a fill character, and for join a delimiter string. A single nq_expr_str(e, op, a, b, flag1, flag2, n, ch, s) with an NqStrOp enum covers them all, the same way nq_expr_unary covers one-argument functions. A NULL expression argument means a null literal (for stripChars() and an open-ended slice).
StrNameSpace is a distinct Expr
col.race.str.replaceAll(...) reads like Polars, and names can't clash with Expr procs or with future namespaces (str.len vs list.len). Converting back is free.
format in Nim
Python's pl.format splits the template on {} and calls concat_str; Nanuq does the same, so no ABI function is needed.
Tasks
1. Bridge
- 1.1Add the Polars features
strings,regex,string_pad,string_reverse, andconcat_str - 1.2Add
nq_expr_strwithNqStrOp, andnq_expr_concat_str; mirror them inffi.nim
2. Nim API
- 2.1Add
StrNameSpace,strand every function listed in the proposal - 2.2Add
concatStrandformat - 2.3Write
tests/test_strings.nim: each function, literal vs regex, strict vs not, nulls,joininagg,formatwith too few or too many arguments,formatnext tostrutils; add it tonanuq.nimbleand.gitignore
3. Docs and integration
- 3.1README lists the namespace;
nimble testandnimble specexamplespass - 3.2Archive the change: remove BACKLOG "More expressions", add CHANGELOG lines
Revisions
603f9ac OpenSpec add-string-expressions: str namespace, concatStr, formatFirst version: design.md, proposal.md, specs/native-bridge/spec.md, specs/strings/spec.md, tasks.md
add-struct-namespace Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
Struct columns (add-nested-dtypes) need their functions: struct.field blocks 11 book sections, pl.struct(...) 9, unnest 8 and value_counts 12 (Polars' expression value_counts returns a struct). The arr namespace for Array columns comes along, as the coverage map pairs them.
It is the fourth change of the 0.5 release.
What Changes
asStruct(exprs)builds a struct column (Python'spl.struct).e.struct:field(name)(alsoe.struct["name"]),field(names)andfield(index),unnest(all fields as columns),renameFields,withFields,jsonEncode.df.unnest(columns, separator)(eager and lazy): fields become columns.Expr.valueCounts(sort, parallel, name, normalize)gives a struct of value and count.e.arr:len,sum,min,max,mean,median,std,var,argMin,argMax,first,last,get,join,contains,countMatches,sort,slice,head,tail,shift,toList,toStruct,explode,eval,agg.
Capabilities
New Capabilities
struct-functions: struct construction, the struct and arr namespaces, unnest and expression valueCounts.
Differences from Polars
- The constructor is
asStruct(the Rust name):structis the namespace,col("a").struct, andstruct(col("a"))could not be told apart from it. asStructtakes expressions only; Python also takes keyword arguments (pl.struct(x=...)): use.alias.struct.withFieldsrefers to the struct's own fields withcolinsidestruct.field, not with Python'spl.field.arr.toStructnames the fieldsfield_0, ...; Python can also take a function.- No
prefixFields/suffixFields(not in Rust Polars 0.55's DSL).
Impact
src/rust/src/lib.rsandsrc/nanuq/ffi.nim:nq_expr_struct,nq_as_struct,nq_expr_value_counts,nq_lf_unnest,nq_expr_arr.src/nanuq.nim:StructNameSpace,ArrayNameSpace.- New
tests/test_structs.nim.
Spec changes
struct-functions modified
Building structs
asStruct(exprs) SHALL build a struct column with one field per expression, named after its output name.
let df = newDataFrame:
bear: ["Ada", "Bo"]
kg: [410, 380]
echo df.select(asStruct(col("bear"), col("kg") * 2).alias("s"))
TBD
- WHEN two expressions with the same output name are put in one struct
- THEN
DuplicateErroris raised
Struct fields
e.struct.field(name) (also e.struct[name]) SHALL give one field as a column, field(names) several, field(index) one by position, and e.struct.unnest all of them; renameFields(names) SHALL rename the fields in order, withFields(exprs) add or replace fields, and jsonEncode give each struct as a JSON string.
let df = newDataFrame:
p: [(x: 1, y: 2.0), (x: 3, y: 4.0)]
echo df.select(col("p").struct.field("x"), col("p").struct["y"].alias("y"),
col("p").struct.jsonEncode.alias("json"))
echo df.select(col("p").struct.renameFields(["a", "b"]).struct.unnest)
TBD
- WHEN
struct.field("z")is evaluated on a struct withoutz - THEN
StructFieldNotFoundErroris raised
Unnesting frames
df.unnest(columns) SHALL replace each struct column by its fields (eager and lazy); with separator, the new columns SHALL be named <column><separator><field>.
let df = newDataFrame:
bear: ["Ada", "Bo"]
den: [(lat: 78.2, lon: 15.6), (lat: 79.0, lon: 16.1)]
echo df.unnest("den")
echo df.unnest("den", separator = "_").columns
TBD
- WHEN a list column is unnested
- THEN
InvalidOperationErrororSchemaErroris raised
Value counts as an expression
e.valueCounts(sort, parallel, name, normalize) SHALL give a struct column with the distinct values and their counts (or fractions with normalize), named count (or proportion) unless name is given.
let df = newDataFrame:
island: ["Biscoe", "Dream", "Biscoe"]
echo df.select(col("island").valueCounts(sort = true)).unnest("island")
TBD
- WHEN
valueCounts(sort = true)is evaluated - THEN the most frequent value comes first
Array functions
e.arr SHALL give a namespace of functions on each array of an Array column: len, sum, min, max, mean, median, std, var, argMin, argMax, first, last, get, join, contains, countMatches, sort, slice, head, tail, shift, toList, toStruct, explode, eval and agg.
let df = newDataFrame:
rgb: [[255, 0, 0], [10, 20, 30]]
echo df.select(col("rgb").arr.sum.alias("sum"), col("rgb").arr.get(1).alias("g"),
col("rgb").arr.toList.alias("list"))
TBD
- WHEN
arr.toStructis evaluated on arrays of width 3 - THEN the result is a struct with fields
field_0,field_1andfield_2
Unchanged in this spec: Structs from column names
Tasks
1. Implementation
- 1.1Crate: struct and arr entry points,
as_struct,value_counts, frame unnest - 1.2
asStruct,StructNameSpace,unnest,Expr.valueCounts,ArrayNameSpace - 1.3Tests in
tests/test_structs.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
5c0aadf 0.5: nested dtypes, list, struct and arr namespaces, nested stringsFirst version: proposal.md, specs/struct-functions/spec.md, tasks.md
add-temporal-types Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 10/10
- Archive
Proposal
Why
Nanuq 0.2 cannot hold a date. Every real table has one: a rider's birth date, a stage date, a finishing time, a gap to the winner. The 0.3 explainer "Aged 19" is built on them (age of a winner on race day, gaps in hours and minutes, finish times across time zones), and the dev log "Designing Nanuq 0.3" names temporal types the critical item of the release.
Nim's standard library makes this harder than in Python: std/times has DateTime and Duration, but no date without a time, no time of day, only local and UTC zones, and a TimeInterval (calendar steps such as 1.months) next to Duration (exact lengths). The design (dev log section 1) keeps the std/times types where they fit and adds two small Nanuq types where they do not.
This change takes up the dates part of the BACKLOG.md entry "More dtypes". It is the fifth change of the 0.3 release.
What Changes
- Data types:
DataTypeKindgainsDate,Datetime,DurationandTime. Datetime and Duration carry atimeUnit(std/times'TimeUnit, limited toNanoseconds,Microseconds,Milliseconds), and Datetime an optionaltimeZone(an IANA name).$gives Polars' names (datetime[μs, Europe/Rome]).schema[c] == DateTimematches any unit and zone. - Nim values:
Date(adistinct int32of days since 1970-01-01, withdate(y, m, d),year,month,monthday,$,+/-days and comparisons) andTimeOfDay(withtimeOfDay(h, m, s, ns)), next to std/times'DateTimeandDuration.series, blocknewDataFrame,lit,toList,df[c, i, T],fillNulland the comparison operators accept them.nanuqexportsstd/times. - Casts:
cast(Date),cast(DateTime, timeUnit = Milliseconds, timeZone = "Europe/Rome"),cast(Duration)andcast(TimeOfDay). - Constructors:
dateRange(start, stop, interval = "1d", closed = ClosedWindow.Both)anddatetimeRange(...)return expressions;duration(weeks = ..., days = ..., hours = ..., ..., nanoseconds = ...)takes ints or expressions. Intervals are Polars strings ("1mo") or std/timesTimeIntervals (1.months), converted bytoPolarsInterval. - Parsing:
str.strptime(T, format, strict, exact, cache),str.toDate,str.toDatetime(format, timeUnit, timeZone, ambiguous)andstr.toTime, with chrono format codes.readCsvandscanCsvtaketryParseDates = false. - The
dtnamespace (adistinct Expr, likestr):year,isoYear,quarter,month,week,weekday,day,ordinalDay,hour,minute,second,millisecond,microsecond,nanosecond,date,time,isLeapYear,daysInMonth,monthStart,monthEnd,timestamp,castTimeUnit,toString/strftime(a format string, orDurationFormat.Iso/Polarsfor durations),truncate,round,offsetBy,convertTimeZone,replaceTimeZone(tz, ambiguous, nonExistent),combine(time)andtotalDays…totalNanoseconds(fractional = false). - Inspection:
glimpseanddescribehandle temporal columns. - Polars features
temporal,dtype-date,dtype-datetime,dtype-duration,dtype-time,timezones,offset_by,range,month_startandmonth_end(already compiled in by the string change) are used.
Not in this change: groupByDynamic and rolling windows, dt.weekday names, business-day functions, dt.epoch variants beyond timestamp, upsample.
Capabilities
New Capabilities
temporal: temporal values, constructors, parsing and thedtnamespace.
Modified Capabilities
data-types: the four temporal kinds, time units and zones, temporal cast targets and the Nim type mapping.csv-io:tryParseDates.native-bridge:NqTimeUnit,NqClosedWindowandNqDtOpjoin the ordered enums; dtypes cross the ABI as anNqDtypeSpecstruct.
Differences from Polars
Expected differences from Polars' Rust and Python APIs:
- Nim value types: Python uses
datetime.date,datetime.datetime,datetime.timedeltaanddatetime.time; Rust uses chrono. Nanuq uses std/times'DateTimeandDurationplus its ownDateandTimeOfDay. - DateTime values are instants. A
DateTimegiven toseriesorlitis stored as its UTC instant, and naive (no zone) unlesstimeZoneis given. Values read back are UTCDateTimes, whatever the column's zone. Python keeps naive datetimes as wall-clock time and returns zone-aware ones in the column's zone. - Style insensitivity: Nim cannot tell
DatetimefromDateTime, so the cast target and the==right-hand side are std/times'DateTime;DataTypeKind.Datetimenames the kind.col(DateTime)selects only naive microsecond datetimes (an exact dtype); use aDataTypefor other units and zones. - Time units reuse std/times'
TimeUnit(Milliseconds, not"ms"); other values raiseValueError. - Intervals accept std/times'
TimeInterval(1.months + 2.days) next to Polars' strings; mixed signs raiseValueError. dateRangeanddatetimeRangereturn expressions only (Python'seager = trueisnewDataFrame().select(...)).- Enums for string options:
ClosedWindow,Ambiguous(Raise,Earliest,Latest,Null),NonExistent(Null,Raise) andDurationFormat(Iso,Polars) are pure enums;Ambiguous.Nullmust always be qualified. dt.toStringtakesDurationFormatfor durations instead of the strings "iso" and "polars";strftimeis an alias, as in Python.describeshows datetime statistics with Polars' cast to string (2026-07-05 00:00:00.000000) and durations in Polars' format (4m 23s), where Python formats them itself.- Names follow Polars in camelCase:
ordinal_day→ordinalDay,convert_time_zone→convertTimeZone,try_parse_dates→tryParseDates.
Impact
src/rust/src/lib.rs:NqDtypeSpecreplaces the dtype code in casts, selectors and schema overrides; temporal series, literals, ranges,duration,strptimeandnq_expr_dtwithNqDtOp.src/nanuq/ffi.nim,src/nanuq.nim: the declarations,Date,TimeOfDay, the temporalDataTypefields, casts, constructors, parsing andDtNameSpace.tests/test_temporal.nim(new); README; BACKLOG "More dtypes" keeps only the remaining dtypes.
Spec changes
csv-io modified
CSV read options
Unchanged in this spec: Scanning CSV, CSV write options, Reading CSV from a stream, Quoting, encoding and new column names, Comment lines
data-types modified
DataType values
Casting
Nim types map to DataType
Unchanged in this spec: DataType constants and predicates, Schemas, Full-range UInt64
native-bridge modified
Nim declarations mirror the C ABI
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release
temporal modified
Temporal values
The API SHALL provide Date (date(y, m, d)) and TimeOfDay (timeOfDay(h, m, s, ns)), and SHALL accept them and std/times' DateTime and Duration wherever Nim values build columns or literals. toList and df[c, i, T] SHALL read them back, as Option for nulls. DateTime values SHALL be stored and read back as UTC instants. nanuq SHALL export std/times.
let df = newDataFrame:
rider: ["Seixas", "Pogačar"]
born: [date(2006, 9, 24), date(1998, 9, 21)]
start: [timeOfDay(13, 10), timeOfDay(13, 12)]
gap: [initDuration(minutes = 4, seconds = 23), initDuration()]
finish: [dateTime(2026, mJul, 4, 17, 21, zone = utc()), nil]
echo df
echo df.filter(col.born > date(2000, 1, 1)).toList("rider", string)
echo df.toList("born", Date)[0].year, " ", df["finish", 1, Option[DateTime]].isNone
TBD
- WHEN a column built from
[date(2026, 7, 4), nil]is read withtoList(df, c, Option[Date]) - THEN the result is
@[some(date(2026, 7, 4)), none(Date)]
- WHEN
timeOfDay(24)is called - THEN
ValueErroris raised
- WHEN a Date column is read with
toList(df, c, DateTime) - THEN
InvalidOperationErroris raised
Temporal ranges and durations
dateRange(start, stop, interval = "1d", closed = ClosedWindow.Both) and datetimeRange(..., timeUnit, timeZone) SHALL return expressions. interval SHALL be a Polars interval string or a TimeInterval, converted by toPolarsInterval, which raises ValueError on mixed signs. duration(weeks, days, hours, ..., nanoseconds) SHALL build a Duration from ints or expressions.
let months = newDataFrame().select(dateRange(date(2026, 1, 31), date(2026, 4, 30), 1.months).alias("day"))
echo months.toList("day", Date)
echo toPolarsInterval(1.years + 2.days)
let gaps = newDataFrame:
h: [73, 0]
m: [56, 4]
echo gaps.select(duration(hours = col.h, minutes = col.m, seconds = 26).alias("gap"))
TBD
- WHEN
dateRange(date(2026, 1, 31), date(2026, 4, 30), 1.months)is selected - THEN the dates are the last days of January to April
- WHEN
dateRange(date(2026, 1, 1), date(2026, 1, 15), "1w", closed = ClosedWindow.Left)is selected - THEN the result has 2 rows
- WHEN
toPolarsInterval(1.days - 2.hours)is called - THEN
ValueErroris raised
Parsing strings
e.str SHALL provide strptime(T, format, strict = true, exact = true, cache = true) for T in Date, DateTime and TimeOfDay, and the shorthands toDate(format), toDatetime(format, timeUnit, timeZone, ambiguous) and toTime(format). Formats SHALL use chrono's codes; an empty format SHALL let Polars infer it. A strict parse SHALL raise PolarsError when a value does not match; a non-strict one SHALL give null. exact = false SHALL allow the format to match part of the string.
let df = newDataFrame:
born: ["17 July 1993", "24 September 2006", "smudged"]
echo df.select(col.born.str.toDate("%d %B %Y", strict = false))
TBD
- WHEN
str.toDate("%d %B %Y")runs over a value "smudged" - THEN
PolarsErroris raised
- WHEN
str.toDatetime("%Y-%m-%d %H:%M", timeZone = "Australia/Adelaide")is selected - THEN the dtype is
datetime[μs, Australia/Adelaide]
Date and time parts
e.dt SHALL return a DtNameSpace with year, isoYear, quarter, month, week, weekday (Monday 1 to Sunday 7), day, ordinalDay, hour, minute, second, millisecond, microsecond, nanosecond, date, time, isLeapYear, daysInMonth, monthStart and monthEnd, each returning an expression with Polars' result dtype.
let df = newDataFrame:
at: [dateTime(2026, mJul, 4, 13, 10, zone = utc()), dateTime(2024, mFeb, 29, zone = utc())]
echo df.select(col.at.dt.year.alias("y"), col.at.dt.weekday.alias("wd"),
col.at.dt.ordinalDay.alias("od"), col.at.dt.date.alias("d"),
col.at.dt.time.alias("t"), col.at.dt.isLeapYear.alias("leap"))
TBD
- WHEN
dt.dayanddt.hourrun over 2026-07-04 13:10 - THEN the results are 4 and 13
- WHEN
dt.yearruns over a string column - THEN
PolarsErroris raised when the query runs
Formatting temporal values
dt.toString(format) and its alias dt.strftime(format) SHALL format dates, datetimes and times with chrono's codes. dt.toString(DurationFormat.Iso) and dt.toString(DurationFormat.Polars) SHALL format durations as ISO 8601 or Polars' short form.
let df = newDataFrame:
at: [dateTime(2026, mJul, 4, 13, 10, zone = utc())]
gap: [initDuration(minutes = 4, seconds = 23)]
echo df.select(col.at.dt.toString("%d %B %Y"), col.gap.dt.toString(DurationFormat.Iso).alias("iso"),
col.gap.dt.toString(DurationFormat.Polars).alias("short"))
TBD
- WHEN a 4 min 23 s duration is formatted with
DurationFormat.IsoandDurationFormat.Polars - THEN the results are "PT4M23S" and "4m 23s"
Temporal arithmetic
Subtracting dates or datetimes SHALL give a Duration. dt SHALL provide truncate(every), round(every), offsetBy(by) (intervals as strings or TimeIntervals), timestamp(timeUnit), castTimeUnit(timeUnit), and on durations totalDays … totalNanoseconds, whole numbers unless fractional = true.
let df = newDataFrame:
born: [date(2006, 9, 24), date(1998, 9, 21)]
race: [date(2026, 3, 21), date(2026, 3, 21)]
echo df.select((col.race - col.born).dt.totalDays.alias("days"),
col.born.dt.offsetBy(19.years).alias("turns_19"),
col.race.dt.truncate(1.months).alias("month"))
TBD
- WHEN 2024-02-29 is offset by
1.years - THEN the result is 2025-02-28
- WHEN
dt.totalDays(fractional = true)runs over 36 hours - THEN the result is 1.5
Time zones
dt.replaceTimeZone(timeZone, ambiguous = Ambiguous.Raise, nonExistent = NonExistent.Raise) SHALL attach a zone to wall-clock times (or remove it with ""), dt.convertTimeZone(timeZone) SHALL show the same instants in another zone, and dt.combine(time) SHALL join a date and a time of day into a datetime.
let stage = newDataFrame:
day: [date(2026, 1, 20)]
finish: [timeOfDay(14, 3)]
let local = col.day.dt.combine(col.finish).dt.replaceTimeZone("Australia/Adelaide")
echo stage.select(local.alias("adelaide"), local.dt.convertTimeZone("Europe/Paris").alias("paris"))
TBD
- WHEN 14:03 in Adelaide on 2026-01-20 is converted to Europe/Paris
- THEN the time is 04:33 and the value read back equals 03:33 UTC
- WHEN
dt.convertTimeZone("Mars/Olympus")runs - THEN
PolarsErroris raised
Unchanged in this spec: Dates from parts, More date parts and time ranges, Business days
Design
Design
Values cross as physical integers
Polars stores Date as i32 days, Datetime and Duration as i64 in their time unit, and Time as i64 nanoseconds. Nim values are converted to these integers on the Nim side (toPhysical), sent with the existing integer buffers, and cast to the temporal dtype in Rust (nq_series_new_temporal, nq_expr_lit_temporal). Reading back goes the other way through nq_expr_to_physical. No date logic lives in Rust.
Dtype specs
A dtype is no longer a single enum code: Datetime carries a unit and a zone, and the categorical change will carry categories. NqDtypeSpec (code, time unit, zone C string, categories pointer and count) crosses the ABI by value wherever a dtype did. Nim keeps the zone strings alive for the call (toSpecs).
Date and TimeOfDay
Date is distinct int32, the same days count Polars stores, so it round-trips without loss and sorts as an integer. TimeOfDay wraps nanoseconds since midnight. Both convert to and from DateTime (toDateTime, toDate, toTimeOfDay). They are deliberately small: calendar arithmetic goes through DateTime or the dt namespace.
Instants, not wall-clock times
A std/times DateTime is always an instant with a zone (local or UTC). Nanuq stores its UTC instant. A naive column therefore holds UTC wall-clock times; a zoned column the same instant in that zone. Reading back always gives UTC DateTimes, because std/times cannot represent IANA zones. This keeps the conversion lossless and documented, at the price of differing from Python for naive local times.
dt as one entry point
As with str, the namespace is a distinct Expr, and Rust has one nq_expr_dt(expr, op, arg expr, string, flag, unit, nonExistent) that switches on NqDtOp, so new functions need no new ABI symbols.
Intervals
toPolarsInterval(TimeInterval) writes Polars' duration language (1y2mo3d4h). A TimeInterval with mixed signs has no single Polars string, so it raises ValueError.
Tasks
1. Bridge
- 1.1Add
NqDtypeSpecand use it for casts, selectors and schema overrides - 1.2Add temporal series, literals,
nq_expr_to_physical, time unit and zone getters - 1.3Add
nq_expr_date_range,nq_expr_duration,nq_expr_strptimeandnq_expr_dtwithNqDtOp; mirror everything inffi.nim
2. Nim API
- 2.1Add the temporal
DataTypeKinds,timeUnit/timeZone,Date,TimeOfDayand the conversions - 2.2Accept temporal values in
series, blocknewDataFrame,lit,toList,[],fillNulland casts - 2.3Add
dateRange,datetimeRange,duration,toPolarsIntervaland the parsing procs;tryParseDates - 2.4Add
DtNameSpaceand every function listed in the proposal; temporalglimpseanddescribe - 2.5Write
tests/test_temporal.nim; add it tonanuq.nimbleand.gitignore
3. Docs and integration
- 3.1README lists temporal types;
nimble testandnimble specexamplespass - 3.2Archive the change: update BACKLOG "More dtypes", add CHANGELOG lines
Revisions
6fa49c8 Add temporal types: Date, Datetime, Duration, Time and the dt namespaceFirst version: design.md, proposal.md, specs/csv-io/spec.md, specs/data-types/spec.md, specs/native-bridge/spec.md, specs/temporal/spec.md, tasks.md
add-testing-helpers Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 2/2
- Archive
Proposal
Why
Tests of code that builds frames need a good equality check: one that says where two frames differ, compares floats with a tolerance, and can ignore row or column order. Python Polars ships it as polars.testing (assert_frame_equal and friends); the roadmap lists "testing helpers" in 0.6, and Nanuq's own tests and the book's checks would read better with it than with equals plus toList.
It is the eighth change of the 0.6 release.
What Changes
- New module
nanuq/testing(no extra dependency) withassertFrameEqual,assertFrameNotEqual,assertSeriesEqual,assertSeriesNotEqual. - Options as in Python:
checkRowOrder,checkColumnOrder,checkDtypes,checkNames(Series),checkOrder(Series),checkExact,rtol,atol. - Failures raise
AssertionDefectwhose message names the first difference (columns, heights, dtypes, or the column, row and both values).
Capabilities
New Capabilities
testing-helpers: assertions comparing frames and Series.
Differences from Polars
- Python raises
AssertionError; Nanuq raisesAssertionDefect, asdoAssertdoes, whichstd/unittestreports as a failed test. - Python's
rel_tol/abs_tolarertol/atol(the names Python used before 1.0 and NumPy uses); there is nocategorical_as_str(compare withcheckDtypes = false). - Messages are Nanuq's own wording, not Polars'.
Impact
- New
src/nanuq/testing.nim, newtests/test_testing.nim.
Spec changes
testing-helpers modified
Comparing frames in tests
assertFrameEqual(left, right, checkRowOrder = true, checkColumnOrder = true, checkDtypes = true, checkExact = false, rtol = 1e-5, atol = 1e-8) in nanuq/testing SHALL return when the frames (or collected LazyFrames) have the same columns, types and rows, with nulls equal to nulls and floats equal within atol + rtol * abs(right) unless checkExact, and raise AssertionDefect naming the first difference otherwise. assertFrameNotEqual SHALL do the opposite.
import nanuq/testing
let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.0, 380.5]))
assertFrameEqual(df, newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.0, 380.5000001])))
try:
assertFrameEqual(df, newDataFrame(series("bear", @["Ada", "Cy"]), series("kg", @[410.0, 380.5])))
except AssertionDefect as e:
echo e.msg
TBD
- WHEN two frames hold the same rows and columns in another order and both order checks are off
- THEN
assertFrameEqualreturns
Comparing Series in tests
assertSeriesEqual(left, right, checkDtypes = true, checkNames = true, checkOrder = true, checkExact = false, rtol = 1e-5, atol = 1e-8) SHALL compare two Series the same way, also checking their names unless checkNames = false; assertSeriesNotEqual SHALL do the opposite.
import nanuq/testing
let a = series("kg", @[410, 380])
assertSeriesEqual(a, series("mass", @[410, 380]), checkNames = false)
assertSeriesNotEqual(a, series("kg", @[410, 381]))
echo "ok"
TBD
- WHEN both Series hold NaN at the same row
- THEN
assertSeriesEqualreturns
Tasks
1. Implementation
- 1.1
src/nanuq/testing.nim: the four assertions - 1.2Tests in
tests/test_testing.nim; spec examples pass; CHANGELOG
Revisions
4ea5dad 0.6: archive the 9 changes, fill spec example outputs, map_elements benchmark, dev log Designing Nanuq 0.6First version: proposal.md, specs/testing-helpers/spec.md, tasks.md
add-top-k-rows-and-date-parts Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 10/10
- Archive
Proposal
Why
The 0.4 explainer ("Counting El Niños") was drafted in Python Polars first. Its findings list the calls the 0.4 API could not mirror. The most used call in the post, df.top_k(5, by="peak"), returns whole rows, and 0.4 had only the one-column Expr.topK. The post also builds dates from year and month columns (pl.date(year, month, 15)) and prints its tables with pl.Config(float_precision=2).
It is the twelfth change of the 0.4 release (#51).
What Changes
- Frame
topK(k, by, reverse)andbottomK(k, by, reverse), eager and lazy. date(year, month, day)with expression parts gives a Date column.setFloatPrecision(n), andfloatPrecisioninsetConfigandwithConfig.- Specs now state two things that already worked:
groupBykeeps first-seen group order, andjoinAsof(coalesce = false)keeps the right key.
Capabilities
New Capabilities
(none)
Modified Capabilities
value-functions: top k rows.temporal: dates from parts.inspection: float precision.temporal-grouping:coalescein the as-of join requirement.dataframe-api: group order.
Differences from Polars
- Python's
top_kdoes not promise an order; Nanuq returns largest first (bottomK: smallest first), which is what Rust Polars does. reverseis one bool for all keys; Python also takes a list.datewith three numbers returns a NimDatevalue, not an expression (uselit(date(2026, 1, 1))for a literal column).- Nanuq's
groupByalways keeps group order; Python's default (maintain_order=False) does not, and Nanuq has nomaintainOrderparameter. datetime(year, month, day, hour, ...)is not added:datetimewould clash with std/times'dateTime(Nim names are style-insensitive). It can come with a better name later.
Impact
- Rust:
nq_lf_top_k,nq_expr_date,nq_set_float_precision,nq_get_float_precision. src/nanuq.nim:topK/bottomKframe overloads,dateexpression, float precision in the display config.- Tests in
tests/test_values.nim,tests/test_temporal.nim,tests/test_inspection.nim.
Spec changes
dataframe-api modified
Expressions and lazy queries
Unchanged in this spec: Automatic memory management, Building and reading data, Reading columns by type, HTML tables, Block syntax for building a DataFrame, Column shorthand, True division, Errors as PolarsError
inspection modified
Display config
Scoped display config
Unchanged in this spec: glimpse, describe, Describe prints temporal values as Python, Table formatting options
temporal modified
Dates from parts
date(year, month, day) SHALL build a Date column when at least one part is an expression; each part SHALL be an integer expression or a number, as Polars' date. Invalid dates (month 13, 30 February) SHALL raise when the query runs. With three numbers date SHALL keep returning a Date value.
let seasons = newDataFrame:
year: [1982, 1997, 2015]
month: [12, 11, 11]
echo seasons.select(date(col.year, col.month, 15).alias("mid"))
echo date(2026, 2, 1)
- WHEN
date(col.year, 1, 1)runs on years 1950 and 1951 - THEN the result is the dates 1950-01-01 and 1951-01-01
- WHEN
date(col.year, 2, 30)runs - THEN a
PolarsErroris raised
Unchanged in this spec: Temporal values, Temporal ranges and durations, Parsing strings, Date and time parts, Formatting temporal values, Temporal arithmetic, Time zones, More date parts and time ranges, Business days
temporal-grouping modified
As-of join
Unchanged in this spec: Dynamic group-by, Rolling group-by, Group keys by name
value-functions modified
Top k rows
LazyFrame and DataFrame SHALL support topK(k, by, reverse = false) and bottomK(k, by, reverse = false), returning the k whole rows with the largest (topK) or smallest (bottomK) values of by, in that order. by SHALL be a column name, a list of names, an expression or a list of expressions; with several keys the later ones break ties. reverse = true SHALL swap the direction. Nulls SHALL come last and ties SHALL keep their original order.
let events = newDataFrame:
start: ["1972 MJJ", "1982 AMJ", "1997 AMJ", "2015 MAM", "2023 MJJ"]
peak: [2.1, 2.2, 2.4, 2.6, 2.0]
echo events.topK(3, by = "peak")
echo events.bottomK(1, by = col.peak)
- WHEN
topK(2, by = "peak", reverse = true)runs - THEN it returns the same rows as
bottomK(2, by = "peak")
- WHEN
topK(10, by = "peak")runs on 5 rows - THEN all 5 rows are returned, largest first
Unchanged in this spec: Ordering values, Picking values, Distinct values, Recoding values, Binning, Value counts
Tasks
1. Top k rows
- 1.1
nq_lf_top_k(RustLazyFrame::top_k/bottom_k) - 1.2
topK/bottomKfor LazyFrame and DataFrame,byas names or expressions - 1.3Tests
2. Dates from parts
- 2.1
nq_expr_date(Rustdatetime(DatetimeArgs)cast to Date) - 2.2
date(year, month, day)with expression parts - 2.3Tests
3. Float precision
- 3.1
nq_set_float_precision/nq_get_float_precision - 3.2
setFloatPrecision,setConfig(floatPrecision),withConfig,resetConfig - 3.3Tests
4. Specs for what already worked
- 4.1
groupBygroup order,joinAsof(coalesce = false)
Revisions
9bcedea Frame topK/bottomK, date(year, month, day) expressions, float precisionFirst version: proposal.md, specs/dataframe-api/spec.md, specs/inspection/spec.md, specs/temporal-grouping/spec.md, specs/temporal/spec.md, specs/value-functions/spec.md, tasks.md
add-typed-errors Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 7/7
- Archive
Proposal
Why
Every failure in Nanuq raises one NanuqError, so a script can't tell a missing column from a strict cast that hit a bad value, and the 0.3 explainer wants exactly that: catch the error a smudged result sheet causes and carry on. Python Polars raises a hierarchy of typed exceptions (ColumnNotFoundError, InvalidOperationError, ...), each matching a Rust PolarsError variant, and Nim picks an except branch by type.
This is the third change of the 0.3 release, following the dev log "Designing Nanuq 0.3", section 6: rename NanuqError to PolarsError, add Python's subtypes, raise Nim's own IOError for IO failures, and add nq_last_error_kind to the ABI.
What Changes
- BREAKING:
NanuqErroris renamedPolarsError, the base of every Polars error. - Subtypes of
PolarsError, named as in Python:ColumnNotFoundError,ComputeError,DuplicateError,InvalidOperationError,NoDataError,OutOfBoundsError,SchemaError,SchemaFieldNotFoundError,ShapeError,StructFieldNotFoundErrorandSqlError. Each Rust variant raises its subtype; a variant wrapped in context raises the subtype of the error inside. - IO failures raise Nim's
IOError(e.g. reading a file that does not exist), not aPolarsError. - Errors Nanuq raises itself in Nim use the closest subtype: reading a column with nulls as a plain type, casting to a dtype Nanuq does not model, describing a frame with no columns and converting an unsupported Datamancer column raise
InvalidOperationError. - The C ABI adds
nq_last_error_kind(), which tells the kind of the last error (NqErrorKind).
Capabilities
New Capabilities
None.
Modified Capabilities
dataframe-api: errors are typed;PolarsErrorreplacesNanuqErrorin every requirement.native-bridge:nq_last_error_kind, andNqErrorKindjoins the enums kept in the same order.combining-frames,csv-io,data-types,datamancer-interop,frame-verbs,inspection,missing-values: requirements that raisedNanuqErrornow raisePolarsError(or a named subtype).
Differences from Polars
Expected differences from Polars' Rust and Python APIs:
- One base type, not Rust's enum: Rust has one
PolarsErrorenum with variants; Nanuq, like Python, has a type per variant. Python's base isPolarsErrortoo. - Names:
SchemaMismatchisSchemaErrorandShapeMismatchisShapeError, as in Python. Python's two SQL errors (SQLInterfaceError,SQLSyntaxError) are oneSqlError, since Nanuq has no SQL yet.StringCacheMismatchandAssertionErrorraise the basePolarsError(Nanuq has no string cache, and Nim'sAssertionDefectis a defect, not an error). - IO: Python raises built-in
FileNotFoundError/OSError; Nanuq raises Nim'sIOError, which is not aPolarsError. - Panics inside Polars raise the base
PolarsErrorwith the panic message; Python raisesPanicException, which is not anException. - Python's warnings (
PolarsWarningand friends) have no counterpart.
Impact
src/rust/src/lib.rs: a thread-local error kind next to the message, set when aPolarsErroris converted;nq_last_error_kind;NqErrorKind.src/nanuq/ffi.nimandsrc/nanuq.nim: the declaration, the error types,raiseLastpicking the type.src/nanuq/datamancer.nim, tests, README and docs:PolarsErrorinstead ofNanuqError.
Spec changes
combining-frames modified
Joins
Join options
Concatenation
csv-io modified
Scanning CSV
Unchanged in this spec: CSV read options, CSV write options, Reading CSV from a stream, Quoting, encoding and new column names, Comment lines
data-types modified
Casting
Unchanged in this spec: DataType values, DataType constants and predicates, Schemas, Nim types map to DataType, Full-range UInt64
dataframe-api modified
Errors as NanuqError
Reason: Replaced by typed errors under the base PolarsError. Migration: Catch PolarsError (or a subtype such as ColumnNotFoundError) instead of NanuqError.
Errors as PolarsError
Any failing FFI call SHALL raise a PolarsError, or Nim's IOError for IO failures, carrying the message from Rust. The type SHALL follow the Rust PolarsError variant: ColumnNotFoundError, ComputeError, DuplicateError, InvalidOperationError, NoDataError, OutOfBoundsError, SchemaError, SchemaFieldNotFoundError, ShapeError, StructFieldNotFoundError and SqlError, all subtypes of PolarsError.
let df = newDataFrame(series("a", [1]), series("s", ["x"]))
try:
discard df.select(col("nope"))
except ColumnNotFoundError as e:
echo e.msg.splitLines[0]
try:
discard df.select(col("s").cast(int))
except PolarsError as e:
echo e.name
try:
discard readCsv("no/such/file.csv")
except IOError:
echo "IOError"
not found: unable to find column "nope"; valid columns: ["a", "s"]
InvalidOperationError
IOError
- WHEN a query selects a column that does not exist
- THEN
ColumnNotFoundErroris raised with the Polars error message
- WHEN a strict cast fails and the code catches
PolarsError - THEN the handler runs, with an
InvalidOperationError
- WHEN
readCsvgets a path that does not exist - THEN
IOErroris raised, and it is not aPolarsError
Building and reading data
Reading columns by type
Unchanged in this spec: Automatic memory management, Expressions and lazy queries, HTML tables, Block syntax for building a DataFrame, Column shorthand, True division
datamancer-interop modified
From Datamancer
Unchanged in this spec: To Datamancer, Nulls to Datamancer, Optional dependency
frame-verbs modified
Dropping and renaming columns
Sorting by several keys
Sampling rows
Unchanged in this spec: Row windows, Unique rows, Row index, Every n-th row, Frame interpolation, Casting by data type, Several filter predicates, Group order parameter, Frame aggregations, Group-by shortcuts, Iterating over groups, Frame fillNan and select without a frame
inspection modified
describe
Unchanged in this spec: glimpse, Display config, Scoped display config, Describe prints temporal values as Python, Table formatting options
missing-values modified
Plain reads refuse nulls
Unchanged in this spec: Nulls are read as Option, Inspecting nulls, Building columns with nulls, CSV null markers, Null expressions, Dropping rows with nulls, Interpolation, Null literal, Filling nulls in whole frames
native-bridge modified
Errors and panics never cross the boundary
Nim declarations mirror the C ABI
Unchanged in this spec: C ABI over Polars with opaque handles, Linking the static library, Columns cross in bulk, Library version check, Formatted cells, Polars version matches a py-polars release
Tasks
1. Bridge
- 1.1Record the kind of the last error next to its message (
NqErrorKind), unwrapping context; panics and Nanuq's own errors areGeneric - 1.2Export
nq_last_error_kind; mirror it and the enum inffi.nim
2. Nim API
- 2.1Rename
NanuqErrortoPolarsErrorand add the subtypes;raiseLastraises the subtype, orIOErrorfor IO - 2.2Nanuq's own errors raise
InvalidOperationError - 2.3Rename everywhere (Datamancer module, tests, README, docs); tests for a missing column, a strict cast, a duplicate column, a missing file and
except PolarsErrorcatching subtypes
3. Docs and integration
- 3.1
nimble testandnimble specexamplespass - 3.2Archive the change and add CHANGELOG lines
Revisions
62e73bd OpenSpec add-typed-errors: PolarsError hierarchy, IOError for IOFirst version: proposal.md, specs/combining-frames/spec.md, specs/csv-io/spec.md, specs/data-types/spec.md, specs/dataframe-api/spec.md, specs/datamancer-interop/spec.md, specs/frame-verbs/spec.md, specs/inspection/spec.md, specs/missing-values/spec.md, specs/native-bridge/spec.md, tasks.md
add-value-functions Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 6/6
- Archive
Proposal
Why
A whole family of Polars expressions works on the values of one column as a set or a sequence: sort it, take the top five, find duplicates, recode values, bin numbers into categories, count how often each value occurs. Nanuq 0.3 has them only at frame level (sort, unique, head), so they can't be used inside agg or over, and recoding or binning needs a when chain. The book ports hit top_k, value_counts, is_unique, replace, cut and sort_by across the O'Reilly chapters 8 and 13 and the user guide.
It is the fourth change of the 0.4 release.
What Changes
- Order:
Expr.sort(descending, nullsLast),argSort,sortBy(by, descending),reverse. - Picking values:
Expr.head(n),tail(n),slice(offset, length),gather(indices),gatherEvery(n, offset),topK(k),bottomK(k),topKBy(by, k, reverse),bottomKBy,indexOf(value),searchSorted(element, side)with aSearchSortedSidepure enum. - Distinct values:
Expr.unique(maintainOrder),argUnique,isUnique,isDuplicated,isFirstDistinct,isLastDistinct,uniqueCounts,approxNUnique. - Recoding and binning:
replace(old, new)andreplace({old: new, ...}),replaceStrictwithdefault,cut(breaks, labels, leftClosed),qcut(quantiles or n, labels, leftClosed, allowDuplicates). - Counting:
valueCounts(column, sort, normalize, name)on DataFrame and LazyFrame.
Capabilities
New Capabilities
value-functions: order, picking, distinct values, recoding, binning and counting.
Differences from Polars
valueCountsis a frame method taking the column (Python:Series.value_counts, orExpr.value_counts, which returns a Struct; Struct columns come in 0.5).replacetakes a Nim mapping literal{"a": "x"}(an array of pairs) where Python takes a dict;replaceStricthas noreturn_dtype(cast the result instead).cutandqcuthave noinclude_breaks(it returns a Struct). They return an Enum, as in Python Polars 2, which deprecatescutin favour ofbin_intervals; Nanuq keeps Rust's namecut.topKBytakesbybeforekso thatkcan keep its default; Python istop_k_by(by, k=5)too, Rust istop_k_by(k, by, reverse).Expr.headandtaildefault to 10 values as in Python (frames default to 5).
Impact
src/rust/src/lib.rs:NqUnaryandNqBinaryFngrow,nq_expr_sort,nq_expr_sort_by,nq_expr_top_k_by,nq_expr_slice,nq_expr_gather_every,nq_expr_replace,nq_expr_cut,nq_lf_value_counts;src/nanuq/ffi.nim,src/nanuq.nim.- New
tests/test_values.nim.
Spec changes
value-functions modified
Ordering values
e.sort(descending, nullsLast) SHALL sort the values of e, e.argSort SHALL return the row indices that sort them, e.sortBy(by, descending) SHALL order e by one or more other columns, and e.reverse SHALL reverse it, so that these work inside agg and over.
let df = newDataFrame:
basin: ["Pacific", "Pacific", "Atlantic", "Atlantic"]
storm: ["Ana", "Bud", "Cleo", "Dan"]
wind: [120, 185, 150, 95]
echo df.groupBy(col.basin).agg(col.storm.sortBy(col.wind, descending = true).first
.alias("strongest")).sort("basin").collect
TBD
- WHEN
col.x.sort(descending = true)is selected on 2, 3, 1 - THEN the result is 3, 2, 1
Picking values
e.head(n = 10), e.tail(n = 10), e.slice(offset, length), e.gather(indices), e.gatherEvery(n, offset = 0), e.topK(k = 5), e.bottomK(k = 5), e.topKBy(by, k = 5, reverse) and e.bottomKBy(...) SHALL return those values of e; e.indexOf(value) SHALL return the index of the first occurrence of value (or null), and e.searchSorted(element, side) the index at which element would be inserted to keep e sorted.
let df = newDataFrame:
year: [1982, 1997, 2015, 2023]
oni: [2.2, 2.4, 2.6, 2.0]
echo df.select(col.year.topKBy(col.oni, k = 2).alias("top2"),
col.oni.topK(2).alias("peak"))
TBD
- WHEN
col.x.gather([0, 2])is selected on 10, 20, 30 - THEN the result is 10, 30
- WHEN
searchSorted(2)runs on 1, 2, 2, 3 with sideLeftandRight - THEN the results are 1 and 3
Distinct values
e.unique(maintainOrder = false) SHALL return the distinct values, isUnique, isDuplicated, isFirstDistinct and isLastDistinct SHALL flag rows by how their value repeats, argUnique SHALL return the index of each value's first occurrence, uniqueCounts the number of occurrences of each distinct value in order of appearance, and approxNUnique an estimate of the number of distinct values.
let df = newDataFrame:
station: ["Lima", "Quito", "Lima", "Paita"]
echo df.withColumns(col.station.isDuplicated.alias("dup"),
col.station.isFirstDistinct.alias("first"))
TBD
- WHEN
unique(maintainOrder = true)runs on b, a, b, c - THEN the result is b, a, c
Recoding values
e.replace(old, new) and e.replace({old: new, ...}) SHALL replace each listed value and keep the others and the data type; e.replaceStrict(...) SHALL require every value to be listed, unless a default is given, and SHALL take the data type of the new values.
let df = newDataFrame:
phase: ["N", "EN", "LN", "EN"]
echo df.withColumns(col.phase.replaceStrict({"EN": "El Niño", "LN": "La Niña"},
default = "neutral").alias("name"))
TBD
- WHEN
replaceStrict({"a": 1})runs on a column holding "a" and "b" - THEN collecting raises
InvalidOperationError
- WHEN
replace([1, 2], [10])is built - THEN
ValueErroris raised
Binning
e.cut(breaks, labels, leftClosed = false) SHALL put each value in the interval between breaks it falls into, as a Categorical labelled like "(-0.5, 0.5]" or with labels (one more than breaks), and e.qcut(quantiles, ...) SHALL do the same at the quantiles of the values, given as probabilities or as a number of equal groups.
let df = newDataFrame:
oni: [-1.6, -0.2, 0.3, 0.9, 2.4]
echo df.withColumns(col.oni.cut([-0.5, 0.5], labels = ["La Niña", "neutral", "El Niño"])
.alias("phase"))
TBD
- WHEN
cut([0.0])runs on -1.0 and 1.0 - THEN the labels are "(-inf, 0]" and "(0, inf]"
Value counts
valueCounts(column, sort = false, normalize = false, name) on a DataFrame or LazyFrame SHALL return each distinct value of column with its number of occurrences in a column count (or its share in proportion with normalize, or the column name), most frequent first with sort.
let df = newDataFrame:
phase: ["neutral", "El Niño", "neutral", "La Niña", "neutral", "El Niño"]
echo df.valueCounts("phase", sort = true)
TBD
- WHEN
valueCounts("x", normalize = true)runs on a, a, b, b - THEN each value has proportion 0.5
Unchanged in this spec: Top k rows
Tasks
1. Implementation
- 1.1
sort,argSort,sortBy,reverseon expressions - 1.2
head,tail,slice,gather,gatherEvery,topK,bottomK,topKBy,bottomKBy,indexOf,searchSorted - 1.3Distinct-value functions
- 1.4
replace,replaceStrict,cut,qcut - 1.5
valueCountson frames - 1.6Tests in
tests/test_values.nim;nimble testandnimble specexamplespass; CHANGELOG
Revisions
570d956 Nanuq 0.4, changes 1-7: math, cumulative, rolling, value functions, horizontal, reshaping, time groupingFirst version: proposal.md, specs/value-functions/spec.md, tasks.md
build-lib-with-nightly Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 5/5
- Archive
Proposal
Why
Nanuq 0.2 runs the PDS-H benchmark (scale factor 1) about 4x slower than py-polars on the same machine: 13.6 s against 3.07 s on an M3 Pro. The performance investigation (BACKLOG.md, Performance) traced almost all of it to how the library is built, not to the wrapper: py-polars is compiled with nightly Rust and Polars' nightly feature (SIMD and other nightly-only code paths) and uses jemalloc. Measured on the same Mac, best of 3:
| Build | PDS-H SF1 | |---|---| | py-polars 2.1 | 3.07 s | | prebuilt lib-v0.2.0 (stable) | 13.6 s | | nightly + polars/nightly | 3.56 s | | nightly + polars/nightly + jemalloc | 3.20 s (1.04x py-polars) |
Polars' git version, the performant feature, CSE and the streaming engine made no real difference. This change was requested by Pietro on 2026-10-31 for 0.3.
What Changes
- Crate features, both off by default so that local builds keep working on stable Rust:
nightly = ["polars/nightly"]andjemalloc = ["dep:tikv-jemallocator"](tikv-jemallocator 0.6, optional), which sets jemalloc as Rust's global allocator. - Release archives (release-lib.yml) are built with a pinned toolchain,
nightly-2026-04-01, and--features "nightly jemalloc"; Windows usesnightlyonly (py-polars uses mimalloc there, and jemalloc does not build for windows-gnu). aarch64 Linux builds setJEMALLOC_SYS_WITH_LG_PAGE=16, as Polars does, so they also run on kernels with 64 KiB pages. Norust-toolchain.toml: stable stays the default. str.toTitlecase, which Polars only has with its nightly feature: available with the release libraries; a stable local build raisesInvalidOperationError.- The release smoke test also runs
tests/test_strings.nimwith-d:nanuqNightly, which checks that the archive was built with the nightly feature. - Polars stays at 0.55.2.
Capabilities
Modified Capabilities
binary-distribution: how release archives are built.strings:str.toTitlecase.
Differences from Polars
- None in behaviour: this matches how py-polars is built.
toTitlecasedepends on the library build, which Python users never see.
Impact
src/rust/Cargo.toml(features, optional dependency),src/rust/src/lib.rs(global allocator,ToTitlecase),src/nanuq/ffi.nim,src/nanuq.nim..github/workflows/release-lib.yml;openspec/config.yamlcontext ("stable Rust").- jemalloc as Rust's global allocator is safe because every Rust allocation is freed by Rust through the
nq_*_freefunctions; Nim never frees Rust memory itself.
Spec changes
binary-distribution modified
Release build configuration
Release archives SHALL be built with a pinned nightly Rust toolchain and the crate features nightly (Polars' nightly feature) and jemalloc (jemalloc as Rust's global allocator), except on Windows, where only nightly is used. Both features SHALL be off by default, so that a local build needs only stable Rust.
- WHEN a contributor runs
nimble buildRustwith stable Rust - THEN the library builds without either feature, and everything except
str.toTitlecaseworks
- WHEN a release archive is smoke-tested
- THEN
str.toTitlecaseworks with it
Unchanged in this spec: Lib releases, Archives are tested before release, Portable binaries, Committed checksums decide what can be downloaded, Download, verify and cache, CPU variant selection
strings modified
Title case
str.toTitlecase SHALL upper-case the first letter of each word and lower-case the rest, when the native library is built with the nightly feature, as the release libraries are. With a library built without it, it SHALL raise InvalidOperationError when the expression is built.
- WHEN
str.toTitlecaseruns over "tour de france" with a release library - THEN the result is "Tour De France"
- WHEN
str.toTitlecaseis called with a library built on stable Rust - THEN
InvalidOperationErroris raised
Unchanged in this spec: The str namespace, Matching, Replacing and stripping, Slicing and padding, Joining strings in an aggregation, Building strings from columns, Splitting and extracting into lists and structs, Many patterns at once, JSON in strings, Escaping and normalizing
Tasks
1. Build
- 1.1Add the
nightlyandjemallocfeatures and the jemalloc global allocator - 1.2Build the release archives with
nightly-2026-04-01and the features; smoke-testtoTitlecase - 1.3Check a local nightly build with both features passes the tests
2. API and docs
- 2.1Add
str.toTitlecasewith a clear error on stable builds - 2.2Update
openspec/config.yaml, README, CHANGELOG and BACKLOG (Performance)
Revisions
418fa96 Archive build-lib-with-nightlyFirst version: proposal.md, specs/binary-distribution/spec.md, specs/strings/spec.md, tasks.md
one-program-builds Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 7/7
- Archive
From the backlog: Cache rendered dev-log posts in CI
Proposal
Why
CI took about 15 minutes a run, and almost all of it was the same work repeated. Every test file (45), every spec's examples (47) and every dev-log page (16) was compiled into its own binary, and each binary links the static Polars library (~310 MB): about 9 s of GNU ld per binary, on top of compiling Nanuq again each time. On main run #175 the test job took 14 min (tests 6m45s, spec examples 5m56s) and the docs job 4m45s (nimble install 1m26s, rendering 2m57s). Pietro asked (2026-11-02) for a single test runner and a single doc runner, able to run one file or all, and for times that actually go down.
What Changes
tests/all.nimruns everytests/test_*.nimin one program. It finds them at compile time, so there is no list to keep. The files that need an optional package (Datamancer, Arraymancer, db_connector) are left out when it is missing. A single file still runs on its own, and unittest filters work.- The spec examples become unittest tests.
tests/specsuite.nimreadsopenspec/specs/*/spec.mdat compile time and turns each example into a test named<capability>:<line>. Its output is captured at the file descriptor and compared with the text block.tests/test_specs.nimholds the specs that need no other package. The Arraymancer, Datamancer and SQLite specs get their own files, because their imports clash with the rest (quantile).tools/specexamples.nimkeeps--update, and now also builds one program instead of one per spec. docs/all.nimrenders the whole site in one program: the posts in file-name order, then the index, the coverage map and the OpenSpec page. Each page renders when its module is initialised, so the posts do not change, and each still renders on its own.useDevlogPostcallsresetConfig(), so one post's display options cannot reach the next.config.nimslinks with lld and leaves out the library's debug info (-fuse-ld=lld -Wl,--strip-debug) on Linux whenld.lldis installed. This takes a link from 9.2 s to 0.7 s.-d:nanuqKeepDebugInfoturns it off. Nim's stack traces do not use DWARF.- CI uses the runners, drops the separate spec-examples step, and caches
~/.nimble(test and docs jobs) and the moto venv.nimble testandnimble docsuse the runners.
Capabilities
Modified Capabilities
ci: tests, spec examples and the site each build as one program; fast linking.spec-examples: the examples run as unittest tests in the test suite.
Differences from Polars
None: this changes how Nanuq is tested and built, not its API.
Impact
- New
tests/all.nim,tests/specsuite.nim,tests/test_specs*.nim,docs/all.nim. tools/specexamples.nim(one program, exports its parser),docs/nanuqtheme.nim,config.nims,nanuq.nimble,.github/workflows/ci.yml.- Measured: test job 14m05s → 2m21s and docs job 4m45s → 2m55s on the first PR run, before caching. Locally, on 4 cores with a cold cache: tests 9m32s → 47 s, spec examples 6m00s → 35 s, docs 4m46s → 1m25s with byte-identical HTML.
- Editing one test file now recompiles the whole suite (~26 s), not one file (~12 s). When iterating on one file, run it on its own.
- Partly covers the backlog entry "Cache rendered dev-log posts in CI". Installs are cached and rendering is one program, but every post is still re-rendered.
Spec changes
ci modified
Tests, example and dev log
Fast linking
Builds in the repository SHALL link with lld, without debug info, on Linux when ld.lld is installed, unless -d:nanuqKeepDebugInfo is given. CI SHALL make sure lld is installed.
- WHEN CI links a program against the static Polars library
- THEN it uses lld and the link takes about a second, not about nine
Unchanged in this spec: Build Rust only when the crate changes, Skip CI for non-code changes, Lib version follows the crate sources
spec-examples modified
Examples are run
Unchanged in this spec: API requirements have examples
Tasks
1. Implementation
- 1.1
tests/all.nim: every test file in one program, optional packages detected - 1.2
tests/specsuite.nim+tests/test_specs*.nim: spec examples as unittest tests - 1.3
tools/specexamples.nim: one program for all specs (own program for specs importing other packages) - 1.4
docs/all.nim: the whole site in one program;useDevlogPostresets the display config - 1.5
config.nims: lld without debug info when available - 1.6CI and nimble tasks use the runners; cache
~/.nimbleand moto - 1.7Measure CI before/after with warm caches (test job 14m05s → 1m16s, docs 4m45s → 1m47s)
Revisions
8308247 Archive one-program-builds: specs ci and spec-examples updatedFirst version: proposal.md, specs/ci/spec.md, specs/spec-examples/spec.md, tasks.md
pin-polars-to-py-release Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
Nanuq pinned the newest Polars crate on crates.io (0.55.2). The Rust crates are released by hand every few months, and 0.55.2 matches py-polars 1.43, while the book and the explainers compare against py-polars 2.1.0, about 940 commits later. The 0.5 and 0.6 ports kept finding the drift: SQL table functions with named options fail, hash and sample give other values, SQL COUNT(*) has another type, Decimal mod is missing. The research thread "Understand how Polars and py-polars versions align" (/mnt/project-files/polars-versions/report.md) recommends pinning the git tag of the py-polars release instead. Pietro asked for it in the 0.6 release (2026-11-01).
It is the twelfth change of the 0.6 release.
What Changes
src/rust/Cargo.toml:polars,polars-core,polars-plan,polars-utilsandpolars-arrowcome fromgit = "https://github.com/pola-rs/polars", tag = "py-2.1.0"(commit 7f902bd), with the workspace's[patch.crates-io]entries copied (a git dependency does not inherit them).- Release builds (
release-lib.yml) use the tag's toolchain,nightly-2026-09-01. - The wrapper adapts to the Polars API changes between 0.55 and py-2.1.0.
- Breaking, as in Polars 2.0:
profileandcat.getCategoriesare gone (both are compile-time errors that say what to use instead);hash(seed)uses one seed. - Behavior that follows Polars 2.0: CSV read without a header names its columns
column_0,column_1, ... (wascolumn_1, ...);topK/bottomKon expressions and series no longer happen to come out sorted (as documented); a left join withoutmaintainOrderno longer keeps the left order (the join example now passesmaintainOrder = Left);unpivotemits rows in row-major order. - BACKLOG "Track the Rust Polars that py-polars ships" is done.
Capabilities
Modified Capabilities
native-bridge: which Polars the crate builds on.streaming:profileremoved.categoricals:cat.getCategoriesremoved.
Differences from Polars
- None added: the point is to remove the version drift. Nanuq now matches py-polars 2.1.0 (same commit); the book and explainers keep py-polars 2.1.0 as their oracle.
Impact
src/rust/Cargo.toml,Cargo.lock,src/rust/src/lib.rs(API updates),.github/workflows/release-lib.yml; spec example outputs that changed with Polars.- A cold build fetches the Polars repository by git (CI caches
target/and the cargo home as before).
Spec changes
categoricals modified
The cat namespace
Unchanged in this spec: Nim enums as Enum columns, Run-time Enum and Categorical
native-bridge modified
Polars version matches a py-polars release
The nanuq_ffi crate SHALL depend on Polars by the git tag of a py-polars release (py-X.Y.Z), the same version the Nanuq Book and the explainers use as their Python oracle, with the [patch.crates-io] entries of Polars' workspace at that tag; release builds SHALL use that tag's Rust toolchain. Moving to a new py-polars release SHALL move the tag, the patches, the toolchain and the Python oracle together.
- WHEN a book chapter runs the same query in Nanuq and in the pinned py-polars
- THEN the outputs agree, including SQL table functions and seeded
hash/sample
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Nim declarations mirror the C ABI, Linking the static library, Columns cross in bulk, Library version check, Formatted cells
streaming modified
Profiling
Reason: Polars 2.0 removed LazyFrame.profile (its timings were misleading under the streaming engine), and the py-2.1.0 crates no longer have it. Migration: use explain to see the plan, and time collect for the run; calling profile is a compile-time error with this message.
Unchanged in this spec: Choosing the engine, Sinks, Partitioned sinks
Tasks
1. Implementation
- 1.1Cargo.toml git tag py-2.1.0 +
[patch.crates-io]; release toolchain nightly-2026-09-01 - 1.2Adapt lib.rs to the API changes;
nimble testandnimble specexamplespass - 1.3BACKLOG item removed, CHANGELOG, known-limitations text updated
Revisions
da2c150 Pin Polars to the py-2.1.0 git tagFirst version: proposal.md, specs/categoricals/spec.md, specs/native-bridge/spec.md, specs/streaming/spec.md, tasks.md
print-dtypes-as-nanuq-code Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
$ on a DataType printed Polars' short names (i64, list[str], struct[2]), the names in table headers. Reviewing the "Designing Nanuq 0.5" post, Pietro asked why. Python prints data types differently (Int64, List(String), Struct({'x': Int64})), and the short names hide struct fields and are not what you write in Nim. Pietro chose (2026-11-01): print a data type as the Nanuq code that builds it.
It is the tenth change of the 0.5 release (#53).
What Changes
- BREAKING
$DataTypegives Nanuq code:Int64,String,Categorical,List(String),Array(Float64, 3),Array(Int64, [2, 3]),Struct({"x": Int64, "y": Float64}),Enum(["low", "high"]); temporal types print as the Nim types they cast to:Date,TimeOfDay,DateTime(Milliseconds, "Europe/Rome"),Duration(Microseconds). Schemas print with it too ({"a": Int64}). - Table headers,
glimpseandtoHtmlkeep Polars' short names, as Polars prints them.
Capabilities
Modified Capabilities
data-types: how data types print.nested-data: how nested data types print.
Differences from Polars
- Python prints
Array(Float64, shape=(3,)),Struct({'x': Int64})(single quotes),Datetime(time_unit='ms', time_zone='Europe/Rome'),TimeandEnum(categories=['low', 'high']); Nanuq prints its own spelling of the same types. - Rust Polars'
Display(and so the table headers) uses the short names.
Impact
src/nanuq.nim: new$forDataType; the old one becomes the internalshortName, used bytoHtmlandglimpse.- Spec example outputs, tests that compare
$dtype, dev-log section 1.
Spec changes
data-types modified
DataType values
DataType constants and predicates
Unchanged in this spec: Schemas, Casting, Nim types map to DataType, Full-range UInt64
nested-data modified
Nested data types
Unchanged in this spec: Nested columns from Nim, Nested values to Nim, Casting to nested types
Tasks
1. Implementation
- 1.1
$DataTypeas Nanuq code;shortNamefor table headers,glimpse,toHtml - 1.2Tests and spec example outputs
- 1.3Dev-log section 1
Revisions
d36b906 0.5: print data types as Nanuq code (print-dtypes-as-nanuq-code)First version: proposal.md, specs/data-types/spec.md, specs/nested-data/spec.md, tasks.md
refine-book-needs-0-6 Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
The book ports against the 0.6 branch (round 3) found two mismatches with Python: readExcel(skipRows = 1) skipped rows before the header, while py-polars' default engine (fastexcel) skips them after it (O'Reilly's top2000 workbook has an empty row under its header); and rolling(..., groupBy = "store") did not compile.
It is the eleventh change of the 0.6 release.
What Changes
readExcelandreadExcelSheets:skipRowsskips rows after the header row; newheaderRow(from 0) says which row holds the names. Without a header,skipRowsstill skips from the top. Breaking only against the unreleased 0.6 branch.rollingandgroupByDynamic:groupBytakes names or expressions (GroupKeys).
Capabilities
Modified Capabilities
excel-io: Reading Excel (header row and skipped rows).temporal-grouping: group keys by name.
Differences from Polars
- Python passes these as
read_options={"header_row": ..., "skip_rows": ...}; Nanuq has them as parameters,headerRowandskipRows.
Impact
src/rust/src/lib.rs(nq_read_excelgainsheader_row),src/nanuq/ffi.nim,src/nanuq.nim; tests intests/test_bookneeds6.nim.
Spec changes
excel-io modified
Reading Excel
Unchanged in this spec: Writing Excel, Reading OpenDocument
temporal-grouping modified
Group keys by name
The groupBy parameter of rolling and groupByDynamic SHALL take a column name, several names, an expression or several expressions (groupBy = "store", ["store", "aisle"], [col("store")]).
let df = newDataFrame(series("day", @[1, 2, 3, 1, 2]), series("store", @["a", "a", "a", "b", "b"]),
series("sales", @[1, 2, 3, 10, 20]))
echo df.rolling("day", "2i", groupBy = "store").agg(col("sales").sum)
TBD
- WHEN
groupBy = [col("store")]is passed - THEN the result is the same as with
groupBy = "store"
Unchanged in this spec: Dynamic group-by, Rolling group-by, As-of join
Tasks
1. Implementation
- 1.1
readExcelheader row and skipped rows as fastexcel;headerRow - 1.2
GroupKeysforgroupByofrollingandgroupByDynamic - 1.3Tests;
nimble testandnimble specexamplespass; CHANGELOG
Revisions
fdee4e0 0.6: explainer needs (bin slicing, str.toInteger, full-range UInt64, CSV quoteChar/encoding/newColumns), book round 3 (readExcel headerRow/skipRows as fastexcel, GroupKeys), BACKLOG lean buildsFirst version: proposal.md, specs/excel-io/spec.md, specs/temporal-grouping/spec.md, tasks.md
ship-prebuilt-binaries Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 11/11
- Archive
Proposal
Why
The first compile of a program that imports Nanuq builds Polars from source with cargo, which takes about ten minutes and needs a Rust toolchain. Before tagging 0.1, users should be able to nimble install nanuq and compile in seconds, on the common platforms, without Rust.
There is a second problem. nimble install copies only srcDir (src/) into the package directory, so an installed Nanuq has no rust/ crate and can't build the library at all (checked with nimble 0.18.2). Today Nanuq only works from a git checkout.
This takes up the BACKLOG.md entries "Prebuilt binaries for users" and "nimble install support" (Distribution). The research behind it is in the dev-log post "Shipping the Rust half" (docs/blog/shipping_rust_binaries.nim).
What Changes
- Release workflow. Pushing a
lib-v<version>tag buildslibnanuq_ffi.aforx86_64-unknown-linux-gnu,aarch64-unknown-linux-gnu,aarch64-apple-darwinandx86_64-pc-windows-gnu. Each x86_64 target also gets alegacy-cpubuild. The archives and their SHA-256 sums are attached to a GitHub Release, and a PR commits the sums to the repository. Lib releases are tagged by hand. - Compile-time download. When no library is available locally, importing
nanuqdownloads the archive for the target platform once into a per-user cache, verifies its checksum and links it. This is the default. A cargo build remains the fallback for any platform or version without a prebuilt library. - CPU variants, as Explorer does them. On Linux x86_64 the CPU is checked at compile time, and the legacy build is picked if it lacks AVX2/FMA-era features.
-d:nanuqLegacyCpuforces the legacy build everywhere. - Lib versioning. The Rust library has its own version (
rust/Cargo.toml), separate from the Nim package version. A version ending in-devnever downloads. CI fails if the Rust sources differ from the last released lib while the version still claims to be that release. - Version check at startup. The library reports its version, and Nanuq refuses to run with a library that doesn't match the version it was compiled for.
nimble installworks. The Rust crate moves fromrust/tosrc/rust/so that it ships with the installed package, and the source fallback works there too.- Policy switch.
-d:nanuqLib=auto|prebuilt|sourcepicks where the library comes from.-d:nanuqNoCargostays as an alias forprebuilt.-d:nanuqLibDiris unchanged. - The README gets an install section.
Capabilities
New Capabilities
binary-distribution: how prebuilt libraries are built, versioned, published, chosen for a platform and CPU, downloaded, verified and cached.
Modified Capabilities
native-bridge: "Linking the static library" changes. The library can now come from the download cache, the policy define is new, the crate lives insrc/rust/, and the library version is checked at runtime.ci: "Build Rust only when rust/ changes" moves to the new path, and there is a new check that lib versions are bumped when the Rust sources change.
Differences from Polars
The Nim API doesn't change. The differences are in how the native code reaches users:
- No wheels. Python Polars ships prebuilt wheels through PyPI at install time. Nanuq downloads its prebuilt library from GitHub Releases at compile time, the way Elixir's Explorer (rustler_precompiled) and r-polars do. The Rust crate
polarsis always built from source by cargo. - CPU variants are picked automatically. Python publishes a separate package for old CPUs (
polars-lts-cpu, nowpolars[rtcompat]) that users have to choose themselves. Nanuq picks the legacy build on Linux by checking the CPU, and otherwise takes a define. - Fewer platforms. Python wheels cover more targets (Intel macOS, musl, Windows MSVC and arm64). Nanuq starts with four, and other platforms build from source.
- Windows uses MinGW. The Windows library targets
x86_64-pc-windows-gnuto link with Nim's default C compiler. Python wheels use MSVC.
Impact
rust/moves tosrc/rust/. This touchesffi.nim,nanuq.nimbletasks, CI cache keys and paths,.gitignore, the OpenSpec config context and the docs that mentionrust/.rust/src/lib.rsgainsnq_version(), declared inffi.nim. This rebuilds the library once in CI.- New
.github/workflows/release-lib.ymland a committed sums file undersrc/nanuq/. src/nanuq/ffi.nim: the source order, download, checksum, cache and CPU detection, all at compile time. The tools needed at compile time arecurlandtar(present on Windows 10+, macOS and mainstream Linux) and the platform's SHA-256 tool.- Contributors working from a git checkout with a built
target/see no change.
Spec changes
binary-distribution modified
Purpose: How users get a prebuilt libnanuq_ffi instead of compiling Polars: how libraries are
built, versioned and published, and how a compile picks, downloads, verifies and
caches the right one.
Lib releases
Pushing a tag lib-v<version>, where <version> equals the version in the crate's Cargo.toml, SHALL publish a GitHub Release with one archive libnanuq_ffi-<version>-<target>.tar.gz per supported target, and a file of SHA-256 sums for all archives. The supported targets SHALL be x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-legacy-cpu, aarch64-unknown-linux-gnu, aarch64-apple-darwin, x86_64-pc-windows-gnu and x86_64-pc-windows-gnu-legacy-cpu.
- WHEN a maintainer pushes
lib-v0.1.0andCargo.tomlsays0.1.0 - THEN a release
lib-v0.1.0appears with six archives and a sums file - AND a pull request is opened that commits those sums to the repository
- WHEN a maintainer runs the release workflow by hand on
mainwith "publish" - ticked, and no
lib-v<version>tag exists for theCargo.tomlversion - THEN the same release and pull request are made, and the tag is created on the
- commit that was built
- WHEN the tag's version differs from
Cargo.toml - THEN the workflow fails without publishing anything
Archives are tested before release
Each archive SHALL be smoke-tested, by compiling and running a Nanuq test against it on its platform, before the release is published.
- WHEN the smoke test fails for one target
- THEN no release is published for that tag
Portable binaries
Linux libraries SHALL link against glibc 2.28 or older symbols, macOS libraries SHALL target macOS 11 or later, and the modern x86_64 builds SHALL require at most the x86-64-v3 instruction set. Legacy-cpu builds SHALL require only baseline x86-64.
- WHEN a program is linked with the Linux library on a system with glibc 2.28
- THEN it links and runs
Committed checksums decide what can be downloaded
The package SHALL contain the lib version it expects and the SHA-256 of every archive for that version. A compile SHALL download only an archive listed there, and SHALL never download when the lib version ends in -dev.
- WHEN the crate version is
0.2.0-dev - THEN no download is attempted and the library is built from source
- WHEN compiling for a target not listed in the sums (e.g.
riscv64gc-unknown-linux-gnu) - THEN no download is attempted and the library is built from source, with a hint
- saying why
Download, verify and cache
When a prebuilt library is needed, the compile SHALL look in a per-user cache directory keyed by lib version and target, and otherwise download the archive, verify its SHA-256 against the committed sum, and unpack it into the cache. Every source the compile uses SHALL be reported with a compiler hint. A checksum mismatch SHALL stop the compile with an error and SHALL NOT fall back to building from source.
- WHEN a program importing
nanuqis compiled on Linux x86_64 with an empty cache - and no local build
- THEN the archive is downloaded once, verified, cached and linked, and no cargo
- build runs
- WHEN another project on the same machine imports the same Nanuq version
- THEN the cached library is linked without a download
- WHEN the downloaded archive's SHA-256 differs from the committed sum
- THEN compilation fails with an error naming the archive, the expected sum and the
- actual sum
- WHEN the download fails (no network) and the lib policy is
auto - THEN the library is built from source, with a hint saying the download failed
CPU variant selection
On x86_64 Linux, when the compile target is the host, the compile SHALL pick the legacy-cpu library if the host CPU lacks any feature the modern build needs. With -d:nanuqLegacyCpu the legacy-cpu library SHALL be picked on every x86_64 target. Otherwise the modern build SHALL be used.
- WHEN compiling on an x86_64 Linux host without AVX2
- THEN the
legacy-cpuarchive is used
- WHEN compiling for Windows x86_64 with
-d:nanuqLegacyCpu - THEN the
x86_64-pc-windows-gnu-legacy-cpuarchive is used
Unchanged in this spec: Release build configuration
ci modified
Build Rust only when the crate changes
Lib version follows the crate sources
CI SHALL fail when the crate sources differ from those at the tag lib-v<version> for the version in Cargo.toml, unless that version ends in -dev.
- WHEN a pull request changes
src/rust/src/lib.rsandCargo.tomlstill says 0.1.0, which has alib-v0.1.0tag- THEN CI fails and says to set the version to the next
-devversion
Unchanged in this spec: Skip CI for non-code changes, Tests, example and dev log, Fast linking
native-bridge modified
Linking the static library
Library version check
The library SHALL report its version through the C ABI. At startup, Nanuq SHALL compare it with the lib version it was compiled for and stop with an error naming both versions if they differ.
- WHEN
-d:nanuqLibDirpoints at a library built from an older crate version - THEN the program stops at startup with an error naming both versions
Unchanged in this spec: C ABI over Polars with opaque handles, Errors and panics never cross the boundary, Nim declarations mirror the C ABI, Columns cross in bulk, Formatted cells, Polars version matches a py-polars release
Design
Design
Context
src/nanuq/ffi.nim finds libnanuq_ffi.a at compile time: -d:nanuqLibDir, else rust/target/release, else it runs cargo build through gorgeEx. CI already builds the library once per change of the crate and passes it to the other jobs.
nimble install copies only srcDir, and installDirs is resolved inside srcDir, so there is no way to ship a top-level rust/ with the package (both checked with nimble 0.18.2). Atlas and nimby clone the whole repository but don't run nimble hooks.
The research and the comparison with other ecosystems are in the dev-log post docs/blog/shipping_rust_binaries.nim. The requirements are in specs/binary-distribution, specs/native-bridge and specs/ci.
Goals / Non-Goals
Goals:
- A user on one of the four platforms compiles a first Nanuq program in seconds, without Rust, whether Nanuq came from nimble, Atlas, nimby or a git clone.
- Contributors who build the crate locally see no change.
- A binary that doesn't match the sources is never linked silently.
Non-Goals:
- A shared library option (it stays in the backlog).
- Intel macOS, musl, Windows MSVC or Windows arm64 builds.
- Automatic lib releases. Tags are pushed by hand.
- Signing the archives. The committed checksums are the trust anchor.
Decisions
The crate moves to src/rust/
This is the only layout nimble installs. ffi.nim finds the crate as currentSourcePath.parentDir.parentDir / "rust", which is src/rust in a checkout and <pkg>/rust in an installed package. Alternatives considered:
- Drop
srcDir. This moves every Nim module and changes import paths for tests and docs. - No source fallback for installed packages. Users on other platforms would have to clone the repository.
nanuq.nimble adds skipDirs for rust/target so that a local nimble install from a checkout doesn't copy gigabytes of build output.
Lib version comes from Cargo.toml; sums come from a committed file
ffi.nim reads the crate version from src/rust/Cargo.toml with staticRead. src/nanuq/lib-sums.txt holds the lib-v version it was generated for and one <sha256> <archive> line per archive, in sha256sum format. A download happens only when the two versions are equal and the version doesn't end in -dev. The release workflow generates the file, and a bot PR commits it. Between a version bump and the release the versions differ, so the library builds from source, which is the right behaviour for unreleased Rust code.
Alternative: one Nim constant per target in a .nim file. That's harder to diff against the release's sums file.
Download with curl, tar and the system SHA-256 tool, at compile time
Everything runs through gorgeEx during compilation: curl -fsSL --retry 2 -o <tmp> <url>, then the platform hash tool (sha256sum, shasum -a 256 or certutil -hashfile <f> SHA256), then tar -xzf into the cache directory, finally writing a .complete marker that later compiles look for, so that none of them links a half-unpacked file. (The plan was to rename a temporary directory into place, but moveDir isn't available in the compile-time VM.) Each compile downloads to its own temporary name. Hashing a 100 MB archive in the Nim VM would take too long.
-d:nanuqReleaseUrl replaces the GitHub releases URL with a mirror, for networks that block GitHub. The committed sums still apply.
Cache root: $XDG_CACHE_HOME or ~/.cache on Linux, ~/Library/Caches on macOS, %LOCALAPPDATA% on Windows, each plus nanuq/<libver>/<target>/. -d:nanuqCacheDir overrides it.
Alternative: a nimble before install hook. Atlas, nimby, submodules and nimble develop don't run it, so it could only warm the cache, which isn't worth a second code path.
Target triple from Nim's target defines
The triple comes from hostOS/hostCPU as seen by the compiler for the target (defined(linux), defined(amd64) and so on). So cross-compiling with --os/--cpu picks the archive for the target. CPU feature detection runs only when the target is x86_64 Linux and the compiler itself runs on x86_64 Linux. It reads the flags line of /proc/cpuinfo and requires avx avx2 bmi1 bmi2 fma f16c movbe (the x86-64-v3 set as listed there).
Building portable archives
- Linux is built inside the
manylinux_2_28container for each architecture. A static lib compiled on a glibc 2.39 runner can reference newer symbols from C dependencies (for example the__isoc23_*redirects), which would fail to link on older systems. - macOS is built on
macos-15withMACOSX_DEPLOYMENT_TARGET=11.0. - Windows is built on
windows-latestwith the MinGW toolchain that is preinstalled there. - Modern x86_64 builds use
RUSTFLAGS=-C target-cpu=x86-64-v3, and legacy-cpu builds use no CPU flags. - Release profile:
lto = "fat"andcodegen-units = 1if they make the archive smaller without making the build too slow. This is measured in the first task.
Every job smoke-tests its archive by running tests/test_basic.nim with -d:nanuqLibDir on its own runner. The Windows job runs the test under the default MinGW compiler, and ffi.nim gains the Windows system libraries Rust needs (ws2_32, userenv, bcrypt, ntdll).
Runtime version check
nq_version() returns CARGO_PKG_VERSION as a static C string. The top level of ffi.nim compares it with the compile-time version and raises a Defect with both versions in the message.
Policy define
const nanuqLib {.strdefine.} = "auto". nanuqNoCargo maps to prebuilt. Every branch emits a {.hint.} naming the source it used, and a {.error.} lists the ways out (install Rust, pass -d:nanuqLibDir, check the network).
Risks / Trade-offs
- [Corporate proxies block the download]
curlhonoursHTTPS_PROXY. A failed download falls back to cargo underauto, and the hint names the URL so the archive can be fetched by hand and passed with-d:nanuqLibDir. - [Release asset deleted or renamed] The download fails and the library builds from source. Assets are never replaced: a fix ships as a new lib version.
- [A cargo build inside the installed package dir] writes
target/intopkgs2/. Nimble doesn't re-verify package checksums after install. If that turns out to matter, the fallback can use the cache as--target-dir. - [Archive size] About 300 MB unstripped before compression. GitHub allows 2 GiB per asset. It's measured in task 1, and LTO is applied if it helps.
- [
/proc/cpuinfomisses a flag on some kernels] The legacy build is picked, which is slower but safe.-d:nanuqLegacyCpuis the manual override.
Migration Plan
- Merge the implementation, with the crate at
src/rust/and version0.1.0. Main builds from source until the first lib release, as it does today. - Pietro pushes
lib-v0.1.0. The workflow publishes the release and opens the sums PR. Merging it turns on downloads for0.1.0. - Pietro tags the package
v0.1.0.
Rollback: delete src/nanuq/lib-sums.txt (or empty it), and every compile builds from source as before.
Tasks
1. Move the crate and measure
- 1.1Move
rust/tosrc/rust/(git mv). Updateffi.nim,nanuq.nimbletasks,.gitignore,ci.ymlpaths and cache keys,openspec/config.yamlcontext, README and the dev-log posts' mentions ofrust/, and addskipDirsforrust/target. Verifynimble testpasses andnimble installinto a temporary--nimbleDircontainsrust/Cargo.tomlbut norust/target. - 1.2Measure the archive (
tar czfoflibnanuq_ffi.a) with the current profile and withlto = "fat",codegen-units = 1. Keep the LTO settings if the archive is clearly smaller and the build stays under ~20 minutes. Record the numbers in the PR description.
2. Version in the library
- 2.1Add
nq_version()tosrc/rust/src/lib.rsandffi.nim, plus the startup check against the version parsed fromCargo.toml. Verify with a test that the versions match, and that a library built with a different crate version stops with an error naming both versions.
3. Release workflow
- 3.1Add
.github/workflows/release-lib.yml(onlib-v*tags andworkflow_dispatchwithout publishing): check the tag againstCargo.toml, run the 6-archive build matrix as in design.md (manylinux_2_28 for Linux, macos-15, windows-latest with MinGW, v3 / legacy-cpu for x86_64), smoke-test each archive withtests/test_basic.nimon its runner, then publish the release with the sums file and open a PR that updatessrc/nanuq/lib-sums.txt. Verify with aworkflow_dispatchrun that all six jobs build and pass their smoke tests. - 3.2Add the Windows system libraries to
ffi.nim's link flags. Verify via the Windows smoke test in 3.1.
4. Compile-time download
- 4.1In
ffi.nim, add thenanuqLibpolicy (auto/prebuilt/source, withnanuqNoCargoasprebuilt), the target triple, the lib version fromCargo.toml, and readinglib-sums.txt. Verify that with-d:nanuqLib=sourceand no local build, cargo runs as before. - 4.2Implement the cache lookup, the download (curl), checksum check (sha256sum / shasum / certutil), unpacking with a
.completemarker (see design.md), and a hint for each source used. Verify against theworkflow_dispatcharchives from 3.1 (served from a local directory, or uploaded to a test pre-release): a clean cache downloads and links, a second compile uses the cache, a corrupted archive stops with the checksum error, and an unknown target falls back to cargo. - 4.3Add CPU detection for x86_64 Linux and
-d:nanuqLegacyCpu. Verify both choices, using a stubbed flags string for the old-CPU case. - 4.4Document installing (nimble, Atlas, git), the defines and the cache location in the README, and update the
ffi.nimmodule doc. Verify the README commands work in a clean container without Rust once a release exists (task 6.1).
5. CI check
- 5.1Add a CI step that fails when
src/rust/differs from taglib-v<version>and the version doesn't end in-dev. Verify on a branch with a fake tag: changinglib.rsfails the step, and a-devversion passes.
6. End to end
- 6.1After Pietro pushes
lib-v0.1.0and the sums PR is merged: in a fresh container without Rust,nimble installthe package from this branch and compile and run the README example. Verify that it finishes in under a minute with a download hint and no cargo hint.
Workflow follow-up
Revisions
f2a95d3 Archive ship-prebuilt-binaries and prepare the 0.1.0 changelogFirst version: .openspec.yaml, design.md, proposal.md, specs/binary-distribution/spec.md, specs/ci/spec.md, specs/native-bridge/spec.md, tasks.md
use-how-for-method-params Archived
- Proposal
- Specs
- Design
- Tasks
- Implement 3/3
- Archive
Proposal
Why
Python Polars calls the "which variant" parameter of rank, corr and interpolate method, which is a Nim keyword. Nanuq worked around it three different ways: rankMethod, correlationMethod and interpolation. The names were long and inconsistent (Pietro, reviewing the 0.4 dev log: "not a fan of the long name correlationMethod").
Part of the 0.4 release (#51). There are no users yet, so the rename needs no deprecation.
What Changes
- BREAKING
rank(rankMethod = ...)becomesrank(how = ...). corr(a, b, correlationMethod = ...)becomescorr(a, b, how = ...)(new in 0.4).interpolate(interpolation = ...)becomesinterpolate(how = ...)(new in 0.4).- api-conventions gains the rule: Python's
methodishowin Nanuq. - Positional calls (
rank(Min),corr(a, b, Spearman)) are unchanged.
Capabilities
Modified Capabilities
api-conventions: themethod→howrule.expressions:rank's parameter name.horizontal-functions:corr's parameter name.missing-values:interpolate's parameter name.
Differences from Polars
- Python:
rank(method="dense"),pl.corr(a, b, method="spearman"),interpolate(method="nearest"). Nanuq:how = Dense,how = Spearman,how = Nearest. - Rust Polars has separate
pearson_corrandspearman_rank_corrfunctions, and takesRankOptions { method, .. }andInterpolationMethodas plain arguments. quantilekeepsinterpolation, which is Python's name there.
Impact
src/nanuq.nim: three parameter names. No ABI change.- Specs, the 0.4 dev-log post and the CHANGELOG mention the new names.
Spec changes
api-conventions modified
Python's method parameter is how
method is a Nim keyword, so no parameter can have that name. Where Python Polars has a method parameter that picks a variant from a closed set, Nanuq SHALL call it how, the name Polars itself uses for join and concat. This applies to rank, corr and interpolate. Where Python uses another name (quantile's interpolation), Nanuq SHALL keep Python's name.
let df = newDataFrame:
x: [1.0, 2.0, 2.0, 4.0]
y: [1.0, 4.0, 4.0, 16.0]
echo df.select(col.x.rank(how = Dense).alias("dense"),
col.x.rank(Min).alias("min"))
echo df.select(corr("x", "y", how = Spearman).alias("spearman"))
shape: (4, 2)
┌───────┬─────┐
│ dense ┆ min │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞═══════╪═════╡
│ 1 ┆ 1 │
│ 2 ┆ 2 │
│ 2 ┆ 2 │
│ 3 ┆ 4 │
└───────┴─────┘
shape: (1, 1)
┌──────────┐
│ spearman │
│ --- │
│ f64 │
╞══════════╡
│ 1.0 │
└──────────┘
- WHEN user code writes
corr("x", "y", how = Spearman)orrank(how = Dense) - THEN it compiles and picks that variant
- WHEN user code writes
rank(Min)orcorr("x", "y", Spearman) - THEN it means the same as naming
how
Unchanged in this spec: Option values are pure enums with Rust Polars names, The conventions are documented, Parameters that take several types use converter types
expressions modified
Ranking
Unchanged in this spec: Conditional expressions, choose macro, Membership and ranges, Arithmetic operators, Rounding, More aggregations, Null fill strategies, Window expressions, Filtering inside expressions, Shape and position aggregations, Boolean aggregations, Entropy, Row count expression, Several window keys and selector concatenation, Null-aware comparisons and closeness, More expression functions
horizontal-functions modified
Correlation
Unchanged in this spec: Horizontal functions, Generated columns
missing-values modified
Interpolation
Unchanged in this spec: Nulls are read as Option, Plain reads refuse nulls, Inspecting nulls, Building columns with nulls, CSV null markers, Null expressions, Dropping rows with nulls, Null literal, Filling nulls in whole frames
Tasks
1. Rename
- 1.1
rank,corr,interpolate: parameterhow - 1.2Tests, spec examples and the 0.4 dev-log post use the new names
- 1.3CHANGELOG entry
Revisions
5803130 Python's method parameter is how: rank, corr, interpolateFirst version: proposal.md, specs/api-conventions/spec.md, specs/expressions/spec.md, specs/horizontal-functions/spec.md, specs/missing-values/spec.md, tasks.md
Specs
The current specs in openspec/specs, as archived changes left them. Changes still open are not applied here.
api-conventionsarraymancer-interoparrow-interopbinary-decimalbinary-distributioncallbackscategoricalscicloud-storagecolumn-selectorscombining-framescsv-iocumulative-functionsdata-typesdatabase-iodataframe-apidatamancer-interopdatasetsdev-logexcel-ioexpression-pluginsexpressionsframe-utilitiesframe-verbshorizontal-functionsinspectionjson-iolist-functionsmath-functionsmissing-valuesnative-bridgenested-dataparquet-ipcplan-serializationreshapingrolling-windowsrow-objectsseriesspec-examplesspec-reviewsqlstreamingstringsstruct-functionstemporaltemporal-groupingtesting-helpersvalue-functions
api-conventions
Purpose: Naming conventions that every part of the Nanuq API follows: Polars names in camelCase, and closed sets of option values as pure enums with Rust Polars names.
Option values are pure enums with Rust Polars names
A parameter that takes one of a closed set of option values SHALL use a {.pure.} enum whose type name and PascalCase value names are those of the corresponding Rust Polars enum (e.g. JoinType.Left for JoinType::Left). When Rust Polars has no such enum, Nanuq SHALL name one after Python Polars' parameter strings, in PascalCase. Strings SHALL NOT be used for closed sets of options. Internal C ABI enums in ffi.nim keep their Nq/nq prefixes and are exempt.
let a = newDataFrame(series("k", [1, 2]))
let b = newDataFrame(series("k", [2, 3]))
echo a.join(b, on = ["k"], how = Left, maintainOrder = Left).shape # JoinType.Left, MaintainOrderJoin.Left
let how = JoinType.Full # outside a typed parameter, qualify the value
echo a.join(b, on = ["k"], how = how).shape
(2, 1)
(3, 2)
- WHEN user code passes
how = Lefttojoin - THEN it compiles and means
JoinType.Left
- WHEN user code passes
how = Left, maintainOrder = Left - THEN each resolves to its own enum's value, as in Rust
- WHEN user code writes
let x = Leftwith several enums exportingLeft - THEN compilation fails as ambiguous, and
let x = JoinType.Leftcompiles
The conventions are documented
The README SHALL state the API conventions (camelCase Polars names, pure enums with Rust names for option values), and every OpenSpec proposal SHALL follow them, listing any exception in its "Differences from Polars" section.
- WHEN a proposal adds a parameter with a closed set of values
- THEN it uses the Rust Polars enum name and values as a pure enum, or explains why not
Python's method parameter is how
method is a Nim keyword, so no parameter can have that name. Where Python Polars has a method parameter that picks a variant from a closed set, Nanuq SHALL call it how, the name Polars itself uses for join and concat. This applies to rank, corr and interpolate. Where Python uses another name (quantile's interpolation), Nanuq SHALL keep Python's name.
let df = newDataFrame:
x: [1.0, 2.0, 2.0, 4.0]
y: [1.0, 4.0, 4.0, 16.0]
echo df.select(col.x.rank(how = Dense).alias("dense"),
col.x.rank(Min).alias("min"))
echo df.select(corr("x", "y", how = Spearman).alias("spearman"))
shape: (4, 2)
┌───────┬─────┐
│ dense ┆ min │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞═══════╪═════╡
│ 1 ┆ 1 │
│ 2 ┆ 2 │
│ 2 ┆ 2 │
│ 3 ┆ 4 │
└───────┴─────┘
shape: (1, 1)
┌──────────┐
│ spearman │
│ --- │
│ f64 │
╞══════════╡
│ 1.0 │
└──────────┘
- WHEN user code writes
corr("x", "y", how = Spearman)orrank(how = Dense) - THEN it compiles and picks that variant
- WHEN user code writes
rank(Min)orcorr("x", "y", Spearman) - THEN it means the same as naming
how
Parameters that take several types use converter types
Where Python Polars lets a parameter take values of different types (a name or a list of names, a duration string or a number) and the parameter needs a default, Nanuq SHALL use a small exported object type with a converter from each accepted type, instead of a generic union (string | openArray[string] = [] does not compile with a default in Nim) or one overload per combination. The existing types are ColumnNames (a name, a seq or an array of names), OptInterval (a std/times interval or a duration string), JoinKey (a column name or an expression) and AsofTolerance (an interval, a duration string, an int or a float). A new parameter of this kind SHALL reuse one of them when it fits, and a new type SHALL be listed here. Converters SHALL only convert into these types, so they apply only where such a parameter appears.
let df = newDataFrame:
year: [1997, 1997, 1998]
months: ["JJA", "SON", "JJA"]
anomaly: [1.5, 2.3, -0.2]
echo df.pivot("months", index = "year", values = "anomaly").columns
echo df.pivot(["months"], index = @["year"], values = "anomaly").columns
@["year", "JJA", "SON"]
@["year", "JJA", "SON"]
- WHEN user code passes
index = "year"orindex = ["year", "month"]topivot - THEN both compile and mean one or two index columns
- WHEN user code calls
joinAsof(other, on = "t")withouttolerance - THEN it compiles, and no tolerance is applied
arraymancer-interop
Purpose: Copying numeric columns between Nanuq and Arraymancer tensors (nanuq/arraymancer), an optional module like nanuq/datamancer.
Columns to tensors
The optional module nanuq/arraymancer SHALL provide toTensor(series, T), toTensor(df, column, T) and toTensor(df, T, columns), copying values into an Arraymancer Tensor[T] for T in int, float and bool; the frame version SHALL give a 2-D tensor with one row per row of the frame. Nulls SHALL become NaN in float tensors and SHALL raise InvalidOperationError for int and bool.
import pkg/arraymancer, nanuq/arraymancer
let df = newDataFrame:
oni: [2.4, 2.6, 2.0]
temp: [14.7, 15.0, 15.2]
let t = df.toTensor(float)
echo t.shape[0], "x", t.shape[1], " ", t[1, 0]
3x2 2.6
- WHEN a float column with a null is copied with
toTensor("a", float) - THEN the tensor holds NaN at that position
Tensors to columns
toSeries(tensor, name) SHALL copy a 1-D tensor into a Series, and toDataFrame(tensor, columns) SHALL copy a 2-D tensor into a frame with one column per tensor column, named columns or column_0, column_1, ...
import pkg/arraymancer, nanuq/arraymancer
echo [[1.0, 2.0], [3.0, 4.0]].toTensor.toDataFrame(["a", "b"])
shape: (2, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ f64 ┆ f64 │
╞═════╪═════╡
│ 1.0 ┆ 2.0 │
│ 3.0 ┆ 4.0 │
└─────┴─────┘
- WHEN
toSeriesis called on a 2-D tensor - THEN
ValueErroris raised
arrow-interop
Purpose: Exchanging columns and frames with other libraries through the Arrow C Data Interface, and zero-copy access to numeric columns from Nim.
Series through the Arrow C Data Interface
s.toArrow SHALL export a Series as an ArrowExport holding the standard ArrowSchema and ArrowArray C structs, without copying the values. Whatever a consumer did not take over SHALL be released when the export goes away. fromArrow(schema, array, name = "") SHALL import a Series from such structs, taking over the array.
var ex = series("kg", @[410, 380]).toArrow
echo ex.schema.format, " ", ex.array.length
let back = fromArrow(ex, name = "mass")
echo back
l 2
shape: (2,)
Series: 'mass' [i64]
[
410
380
]
- WHEN an export's array is imported with
fromArrow - THEN the export's
array.releaseis nil and the Series reads the same values
Frames through the Arrow C stream interface
df.toArrow SHALL export a frame as an ArrowArrayStream of record batches (struct arrays), and fromArrow(stream) SHALL read a whole stream into a frame and release it.
let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.0, 380.5]))
var stream = df.toArrow
echo fromArrow(stream)
shape: (2, 2)
┌──────┬───────┐
│ bear ┆ kg │
│ --- ┆ --- │
│ str ┆ f64 │
╞══════╪═══════╡
│ Ada ┆ 410.0 │
│ Bo ┆ 380.5 │
└──────┴───────┘
- WHEN a frame with List, Struct and Datetime columns goes through
toArrowandfromArrow - THEN the result equals the frame
Zero-copy views
s.view(T) and df.view(column, T) SHALL give a ColumnView[T] over a numeric column's values without copying, with [], len, items and toOpenArray. T SHALL match the column's type exactly and the column SHALL have no nulls, else InvalidOperationError.
import std/math
let df = newDataFrame(series("kg", @[410.0, 380.5, 455.0]))
let v = df.view("kg", float)
echo v.len, " ", v[1], " ", sum(v.toOpenArray)
3 380.5 1245.5
- WHEN an Int64 column is viewed as
float - THEN
InvalidOperationErroris raised
- WHEN a column with a null is viewed
- THEN
InvalidOperationErroris raised
binary-decimal
Purpose: Binary (raw bytes) and Decimal (exact) columns, the bin namespace, string encodings and bitwise expressions.
Binary data
Binary SHALL be a data type of raw bytes. series(name, strings, Binary) SHALL build a Binary column whose values are the strings' bytes (any bytes), and toList(column, string) SHALL read them back unchanged.
let s = series("sig", ["\x00\xff", "bear"], Binary)
echo s.dtype
let df = newDataFrame(s)
echo df
echo df.toList("sig", string) == @["\x00\xff", "bear"]
Binary
shape: (2, 1)
┌─────────────┐
│ sig │
│ --- │
│ binary │
╞═════════════╡
│ b"\x00\xff" │
│ b"bear" │
└─────────────┘
true
- WHEN a String column is cast to
Binary - THEN its values read back as the same strings
Decimal data
Decimal(precision = 38, scale = 0) SHALL be the exact decimal type, with precision 1 to 38 and scale 0 to precision (else ValueError). Strings SHALL become decimals with series(name, strings, Decimal(p, s)) or str.toDecimal(scale), and Decimal columns SHALL read back as string (exact) or float.
let df = newDataFrame(series("price", ["1.25", "10.50", "0.10"], Decimal(10, 2)))
echo df
echo df.select(col("price").sum)
echo df.toList("price", float)
shape: (3, 1)
┌───────────────┐
│ price │
│ --- │
│ decimal[10,2] │
╞═══════════════╡
│ 1.25 │
│ 10.50 │
│ 0.10 │
└───────────────┘
shape: (1, 1)
┌───────────────┐
│ price │
│ --- │
│ decimal[38,2] │
╞═══════════════╡
│ 11.85 │
└───────────────┘
@[1.25, 10.5, 0.1]
- WHEN
Decimal(40, 2)is called - THEN
ValueErroris raised
Binary functions
e.bin SHALL provide contains, startsWith, endsWith (with a string of bytes or an expression), encode(BinaryEncoding) (hex or base64 text), decode(BinaryEncoding) and size(unit = SizeUnit.Bytes); str.encode(BinaryEncoding) SHALL encode strings' UTF-8 bytes.
let df = newDataFrame(series("b", ["bear", "cub"], Binary))
echo df.select(col("b").bin.encode(BinaryEncoding.Hex).alias("hex"),
col("b").bin.startsWith("be").alias("be"), col("b").bin.size.alias("n"))
echo newDataFrame(series("s", @["hi"])).select(col("s").str.encode(BinaryEncoding.Base64))
shape: (2, 3)
┌──────────┬───────┬─────┐
│ hex ┆ be ┆ n │
│ --- ┆ --- ┆ --- │
│ str ┆ bool ┆ u32 │
╞══════════╪═══════╪═════╡
│ 62656172 ┆ true ┆ 4 │
│ 637562 ┆ false ┆ 3 │
└──────────┴───────┴─────┘
shape: (1, 1)
┌──────┐
│ s │
│ --- │
│ str │
╞══════╡
│ aGk= │
└──────┘
- WHEN a Binary column is encoded to hex, cast to Binary and decoded from hex
- THEN the values equal the original
Bitwise operations
Integer expressions SHALL provide bitwiseCountOnes, bitwiseCountZeros, bitwiseLeadingOnes, bitwiseLeadingZeros, bitwiseTrailingOnes, bitwiseTrailingZeros (per value) and bitwiseAnd, bitwiseOr, bitwiseXor (aggregations).
let df = newDataFrame(series("flags", @[0b0110'u8, 0b0011'u8]))
echo df.select(col("flags").bitwiseCountOnes.alias("ones"),
col("flags").bitwiseTrailingZeros.alias("tz"))
echo df.select(col("flags").bitwiseAnd.alias("and"), col("flags").bitwiseOr.alias("or"))
shape: (2, 2)
┌──────┬─────┐
│ ones ┆ tz │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞══════╪═════╡
│ 2 ┆ 1 │
│ 2 ┆ 0 │
└──────┴─────┘
shape: (1, 2)
┌─────┬─────┐
│ and ┆ or │
│ --- ┆ --- │
│ u8 ┆ u8 │
╞═════╪═════╡
│ 2 ┆ 7 │
└─────┴─────┘
- WHEN
bitwiseCountOnesis applied to a String column - THEN
PolarsErroris raised
Binary slicing and bytes
The bin namespace SHALL provide slice(offset, length), head(n), tail(n) (negative values count from the end) and get(index, nullOnOob = false), which gives the byte as UInt8; index MAY be an expression. Reading a single Binary cell as string SHALL give its raw bytes, zero bytes included.
let df = newDataFrame(series("m", @["\x03\x04\x10\x11", "ab"], Binary))
echo df.select(col("m").bin.get(1).alias("second"),
col("m").bin.slice(2, 2).bin.encode(BinaryEncoding.Hex).alias("tail_hex"))
shape: (2, 2)
┌────────┬──────────┐
│ second ┆ tail_hex │
│ --- ┆ --- │
│ u8 ┆ str │
╞════════╪══════════╡
│ 4 ┆ 1011 │
│ 98 ┆ │
└────────┴──────────┘
- WHEN
bin.get(9, nullOnOob = true)reads a 4-byte value - THEN the result is null
Strings to integers
str.toInteger(base = 10, dtype = Int64, strict = true) SHALL parse strings as integers in base (2 to 36, or a column of bases); with strict = false, values that do not parse SHALL be null instead of raising.
let df = newDataFrame(series("k", @["zz", "10", "?"]))
echo df.select(col("k").str.toInteger(base = 36, strict = false))
shape: (3, 1)
┌──────┐
│ k │
│ --- │
│ i64 │
╞══════╡
│ 1295 │
│ 36 │
│ null │
└──────┘
- WHEN a value does not parse and
strictis true - THEN a
PolarsErroris raised
binary-distribution
Purpose: How users get a prebuilt libnanuq_ffi instead of compiling Polars: how libraries are
built, versioned and published, and how a compile picks, downloads, verifies and
caches the right one.
Lib releases
Pushing a tag lib-v<version>, where <version> equals the version in the crate's Cargo.toml, SHALL publish a GitHub Release with one archive libnanuq_ffi-<version>-<target>.tar.gz per supported target, and a file of SHA-256 sums for all archives. The supported targets SHALL be x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-legacy-cpu, aarch64-unknown-linux-gnu, aarch64-apple-darwin, x86_64-pc-windows-gnu and x86_64-pc-windows-gnu-legacy-cpu.
- WHEN a maintainer pushes
lib-v0.1.0andCargo.tomlsays0.1.0 - THEN a release
lib-v0.1.0appears with six archives and a sums file - AND a pull request is opened that commits those sums to the repository
- WHEN a maintainer runs the release workflow by hand on
mainwith "publish" - ticked, and no
lib-v<version>tag exists for theCargo.tomlversion - THEN the same release and pull request are made, and the tag is created on the
- commit that was built
- WHEN the tag's version differs from
Cargo.toml - THEN the workflow fails without publishing anything
Archives are tested before release
Each archive SHALL be smoke-tested, by compiling and running a Nanuq test against it on its platform, before the release is published.
- WHEN the smoke test fails for one target
- THEN no release is published for that tag
Portable binaries
Linux libraries SHALL link against glibc 2.28 or older symbols, macOS libraries SHALL target macOS 11 or later, and the modern x86_64 builds SHALL require at most the x86-64-v3 instruction set. Legacy-cpu builds SHALL require only baseline x86-64.
- WHEN a program is linked with the Linux library on a system with glibc 2.28
- THEN it links and runs
Committed checksums decide what can be downloaded
The package SHALL contain the lib version it expects and the SHA-256 of every archive for that version. A compile SHALL download only an archive listed there, and SHALL never download when the lib version ends in -dev.
- WHEN the crate version is
0.2.0-dev - THEN no download is attempted and the library is built from source
- WHEN compiling for a target not listed in the sums (e.g.
riscv64gc-unknown-linux-gnu) - THEN no download is attempted and the library is built from source, with a hint
- saying why
Download, verify and cache
When a prebuilt library is needed, the compile SHALL look in a per-user cache directory keyed by lib version and target, and otherwise download the archive, verify its SHA-256 against the committed sum, and unpack it into the cache. Every source the compile uses SHALL be reported with a compiler hint. A checksum mismatch SHALL stop the compile with an error and SHALL NOT fall back to building from source.
- WHEN a program importing
nanuqis compiled on Linux x86_64 with an empty cache - and no local build
- THEN the archive is downloaded once, verified, cached and linked, and no cargo
- build runs
- WHEN another project on the same machine imports the same Nanuq version
- THEN the cached library is linked without a download
- WHEN the downloaded archive's SHA-256 differs from the committed sum
- THEN compilation fails with an error naming the archive, the expected sum and the
- actual sum
- WHEN the download fails (no network) and the lib policy is
auto - THEN the library is built from source, with a hint saying the download failed
CPU variant selection
On x86_64 Linux, when the compile target is the host, the compile SHALL pick the legacy-cpu library if the host CPU lacks any feature the modern build needs. With -d:nanuqLegacyCpu the legacy-cpu library SHALL be picked on every x86_64 target. Otherwise the modern build SHALL be used.
- WHEN compiling on an x86_64 Linux host without AVX2
- THEN the
legacy-cpuarchive is used
- WHEN compiling for Windows x86_64 with
-d:nanuqLegacyCpu - THEN the
x86_64-pc-windows-gnu-legacy-cpuarchive is used
Release build configuration
Release archives SHALL be built with a pinned nightly Rust toolchain and the crate features nightly (Polars' nightly feature) and jemalloc (jemalloc as Rust's global allocator), except on Windows, where only nightly is used. Both features SHALL be off by default, so that a local build needs only stable Rust.
- WHEN a contributor runs
nimble buildRustwith stable Rust - THEN the library builds without either feature, and everything except
str.toTitlecaseworks
- WHEN a release archive is smoke-tested
- THEN
str.toTitlecaseworks with it
callbacks
Purpose: Nim procs and closures called by Polars: element, batch, fold, name and group callbacks.
Typed element callbacks
e.mapElements(f) SHALL call the Nim proc or closure f: proc (x: T): U on each value of e, read as T (as toList reads it: objects and named tuples for structs, seqs for lists), and give a column of dataType(U). Nulls SHALL stay null without a call unless T is an Option. An exception in f SHALL raise ComputeError with its message when the query runs.
type Bear = object
name: string
kg: int
let df = newDataFrame:
name: ["Ada", "Bo", "Cy"]
kg: [410, nil, 500]
let tag = proc (b: Bear): string = b.name & " (" & $b.kg & " kg)"
echo df.select(col("kg").mapElements(proc (x: int): float = x / 1000).alias("t"),
asStruct(col("name"), col("kg").fillNull(0)).mapElements(tag).alias("tag"))
shape: (3, 2)
┌──────┬──────────────┐
│ t ┆ tag │
│ --- ┆ --- │
│ f64 ┆ str │
╞══════╪══════════════╡
│ 0.41 ┆ Ada (410 kg) │
│ null ┆ Bo (0 kg) │
│ 0.5 ┆ Cy (500 kg) │
└──────┴──────────────┘
- WHEN the callback raises
ValueError("no bears") - THEN collecting raises
ComputeErrorwhose message holds "no bears"
Batch callbacks
e.mapBatches(f) SHALL call f: proc (s: Series): Series with the whole column, or in a group-by with each group's values; the result SHALL keep the input type unless returnDtype is given, and with returnsScalar a group-by SHALL get one value per group instead of a list.
let df = newDataFrame:
cubs: [1, 0, 1]
kg: [410, 380, 500]
echo df.select(col("kg").mapBatches(proc (s: Series): Series = s * 2))
echo df.groupBy("cubs").agg(col("kg").mapBatches(proc (s: Series): Series = s.max,
returnsScalar = true)).sort("cubs")
shape: (3, 1)
┌──────┐
│ kg │
│ --- │
│ i64 │
╞══════╡
│ 820 │
│ 760 │
│ 1000 │
└──────┘
shape: (2, 2)
┌──────┬─────┐
│ cubs ┆ kg │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞══════╪═════╡
│ 0 ┆ 380 │
│ 1 ┆ 500 │
└──────┴─────┘
- WHEN
mapBatches(proc (s: Series): Series = s / 10, Float64)runs on an integer column - THEN the result is a
f64column
Folds
fold(acc, f, exprs) SHALL combine columns left to right with f: proc (acc, x: Series): Series, starting from acc; reduce(f, exprs) SHALL start from the first column, and cumFold and cumReduce SHALL keep each step as a struct field.
let df = newDataFrame:
a: [1, 2]
b: [10, 20]
c: [100, 200]
echo df.select(fold(lit(0), proc (acc, x: Series): Series = acc + x, col("*")).alias("sum"))
shape: (2, 1)
┌─────┐
│ sum │
│ --- │
│ i32 │
╞═════╡
│ 111 │
│ 222 │
└─────┘
- WHEN
reducewith+runs on columns a and b - THEN the result is 11 and 22
Name and group callbacks
name.map(f) SHALL rename outputs with f: proc (name: string): string, and groupBy(...).mapGroups(f) SHALL call f: proc (df: DataFrame): DataFrame on each group, in order of first occurrence, and concatenate the results.
let df = newDataFrame:
den: ["A", "B", "A"]
kg: [410, 380, 500]
echo df.select(col("*").name.map(proc (n: string): string = n.toUpperAscii))
echo df.groupBy("den").mapGroups(proc (g: DataFrame): DataFrame = g.sort("kg", descending = true).head(1))
shape: (3, 2)
┌─────┬─────┐
│ DEN ┆ KG │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ A ┆ 410 │
│ B ┆ 380 │
│ A ┆ 500 │
└─────┴─────┘
shape: (2, 2)
┌─────┬─────┐
│ den ┆ kg │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ A ┆ 500 │
│ B ┆ 380 │
└─────┴─────┘
- WHEN
mapGroupsruns on an empty frame - THEN the result is an empty frame with the same columns
categoricals
Purpose: Categorical and Enum columns: Nim enums as Polars Enums, run-time Enum and Categorical dtypes, and the cat namespace.
Nim enums as Enum columns
A Nim enum type SHALL map to a Polars Enum whose categories are $ of its values in order. series, the block form of newDataFrame, cast(T), toList, df[c, i, T], comparisons and isIn SHALL accept the enum type or its values. Reading a value that is not in the enum SHALL raise InvalidOperationError.
type Monument = enum
Sanremo = "Milano-Sanremo", Flanders = "Ronde van Vlaanderen",
Roubaix = "Paris-Roubaix", Liege = "Liège-Bastogne-Liège", Lombardia = "Il Lombardia"
let wins = newDataFrame:
race: ["Il Lombardia", "Milano-Sanremo", "Paris-Roubaix"]
winner: ["Pogačar", "Pogačar", "van der Poel"]
let byRace = wins.withColumns(col.race.cast(Monument)).sort("race")
echo byRace
echo byRace.toList("race", Monument)
echo byRace.filter(col.race == Roubaix).toList("winner", string)
shape: (3, 2)
┌────────────────┬──────────────┐
│ race ┆ winner │
│ --- ┆ --- │
│ enum ┆ str │
╞════════════════╪══════════════╡
│ Milano-Sanremo ┆ Pogačar │
│ Paris-Roubaix ┆ van der Poel │
│ Il Lombardia ┆ Pogačar │
└────────────────┴──────────────┘
@[Milano-Sanremo, Paris-Roubaix, Il Lombardia]
@["van der Poel"]
- WHEN a column of Monument names is cast to
Monumentand sorted - THEN the rows follow the order of the enum, not the alphabet
- WHEN a string that is not a category is cast to
Monumentstrictly - THEN
InvalidOperationErroris raised
Run-time Enum and Categorical
Enum(categories) SHALL build an Enum dtype from strings, raising ValueError on duplicates, and Categorical SHALL be the dtype of strings with categories found in the data. Both SHALL read back as strings.
let df = newDataFrame:
team: ["UAE", "Visma", "UAE"]
level: ["high", "low", "high"]
let t = df.select(col.team.cast(Categorical), col.level.cast(Enum(["low", "high"])))
echo t.schema
echo t.sort("level").toList("level", string)
{"team": Categorical, "level": Enum(["low", "high"])}
@["low", "high", "high"]
- WHEN
dtype(df, c).categoriesis read for a column cast toEnum(["low", "high"]) - THEN it is
@["low", "high"]
The cat namespace
e.cat SHALL give access to lenBytes, lenChars, startsWith(prefix), endsWith(suffix) and slice(offset, length) on Categorical and Enum columns. e.toPhysical SHALL give the category indices. getCategories, removed in Polars 2.0, SHALL be a compile-time error pointing to unique() and the dtype's categories.
type Medal = enum Gold, Silver, Bronze
let df = newDataFrame:
medal: [Silver, Gold, Silver]
echo df.select(col.medal.cat.lenChars)
echo df.select(col.medal.toPhysical).toList("medal", int)
echo df.dtype("medal").categories
shape: (3, 1)
┌───────┐
│ medal │
│ --- │
│ u32 │
╞═══════╡
│ 6 │
│ 4 │
│ 6 │
└───────┘
@[1, 0, 1]
@["Gold", "Silver", "Bronze"]
- WHEN the categories of an Enum column holding only Silver and Gold are needed
- THEN
dtype(df, c).categoriesgives Gold, Silver and Bronze
ci
Purpose: Continuous integration and publishing for the repository (.github/workflows/ci.yml).
Build Rust only when the crate changes
CI SHALL build libnanuq_ffi.a in a single job whose cache key is a hash of the crate sources in src/rust/, and SHALL share the library with the other jobs, which compile with -d:nanuqNoCargo.
- WHEN a push changes only Nim code or docs
- THEN the library comes from cache and no Rust toolchain or cargo build runs
- WHEN a push changes files in
src/rust/ - THEN the library is rebuilt, reusing cached compiled dependencies
Skip CI for non-code changes
CI SHALL NOT run for pushes or pull requests that only change Markdown files, LICENSE, .gitignore, openspec/ or .claude/, except openspec/specs/, whose examples CI runs. On main, CI SHALL also run for pushes that change openspec/, BACKLOG.md or tools/specview.nim, so the published OpenSpec page stays current.
- WHEN a pull request only changes files under
openspec/changes/ - THEN no CI run starts
- WHEN a commit that only changes files under
openspec/changes/lands onmain - THEN CI runs and the site is deployed with the updated OpenSpec page
- WHEN a pull request changes
openspec/specs/expressions/spec.md - THEN CI runs, including the spec examples
- WHEN a change touches
docs/ - THEN CI runs, so the dev log is rebuilt
Tests, example and dev log
CI SHALL run the test suite, which includes the spec examples, as one program (tests/all.nim), and the example, and render the site as one program (docs/all.nim): the nimib dev-log posts in docs/blog, then the index page docs/index.nim and the living pages (the Polars coverage page and the OpenSpec page). On main, after these succeed, it SHALL deploy them to GitHub Pages, with the index as the site root.
- WHEN a commit lands on
mainand the test and docs jobs pass - THEN the dev log and the living pages are deployed to GitHub Pages, and the site root lists the posts
- WHEN a pull request changes behavior that a spec example shows
- THEN the test job fails until the example's output is updated
- WHEN a pull request adds
tests/test_x.nim - THEN the test job runs it as part of
tests/all.nim, with no list to update
Lib version follows the crate sources
CI SHALL fail when the crate sources differ from those at the tag lib-v<version> for the version in Cargo.toml, unless that version ends in -dev.
- WHEN a pull request changes
src/rust/src/lib.rsandCargo.tomlstill says 0.1.0, which has alib-v0.1.0tag- THEN CI fails and says to set the version to the next
-devversion
Fast linking
Builds in the repository SHALL link with lld, without debug info, on Linux when ld.lld is installed, unless -d:nanuqKeepDebugInfo is given. CI SHALL make sure lld is installed.
- WHEN CI links a program against the static Polars library
- THEN it uses lld and the link takes about a second, not about nine
cloud-storage
Purpose: Reading and writing object stores (S3, Google Cloud Storage, Azure, HTTP) by URI, with Python's storage options.
Cloud URIs
Every scan* and read* function for CSV, Parquet, IPC and NDJSON files SHALL accept a cloud URI (s3://, gs://, az://, abfss://, hf://, http://, https://) in place of a local path, globs included. isCloudPath(path) SHALL tell such URIs from local paths.
echo isCloudPath("s3://polar-bears/census.parquet")
echo isCloudPath("https://example.org/bears.csv")
echo isCloudPath("data/bears.csv")
true
true
false
- WHEN
readParquet("http://127.0.0.1:<port>/bears.parquet")runs against a local - HTTP server
- THEN the frame equals the file's
Storage options
The cloud-capable reads, scans, writes and sinks SHALL take storageOptions, key/value pairs as Python's storage_options (aws_region, aws_endpoint_url, google_service_account, azure_storage_account_name, ...). Without them, credentials SHALL come from the environment as in Polars. Unknown keys SHALL be ignored, as in Polars; a failed request SHALL raise IOError.
let opts = {"aws_region": "eu-west-1", "aws_skip_signature": "true"}
let lf = scanParquet("s3://polar-bears/census.parquet", storageOptions = opts)
echo lf is LazyFrame
true
- WHEN
readParquet("s3://no-such-bucket/x.parquet", storageOptions = opts)runs - against a local S3
- THEN
IOErroris raised
Writing to object stores
writeParquet, writeCsv, writeIpc, writeNdjson and the sinks (also partitioned) SHALL write to a cloud URI, with storageOptions; the eager writes SHALL go through a streaming sink.
let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380]))
let opts = {"aws_endpoint_url": "http://127.0.0.1:9000", "aws_allow_http": "true"}
let sink = df.lazy.sinkParquet("s3://polar-bears/out.parquet", lazy = true,
storageOptions = opts)
echo sink is LazyFrame # collect(sink) writes the file
true
- WHEN a frame is written to
s3://nanuq/bears.parqueton a local S3 (moto) and read - back with the same
storageOptions - THEN the frames are equal
column-selectors
Purpose: Selecting several columns at once, by Nim type, by name, by regex or all of them, minus excluded names, and renaming the outputs of such expressions.
Selecting by Nim type
col SHALL accept Nim types and typeclasses and return a Selector.
SomeNumber,SomeInteger,SomeSignedInt,SomeUnsignedIntandSomeFloatSHALL select the matching Polars dtype category.- A concrete type SHALL select the dtype
dataTypegives it. - Several types SHALL select their union.
- A type without a dtype SHALL not compile.
let df = newDataFrame(series("station", ["N", "S"]), series("bears", [3, 5]),
series("weight", [410.5, 380.0]))
echo df.select(col(SomeNumber)).columns
echo df.select(col(float, string)).columns
@["bears", "weight"]
@["station", "weight"]
- WHEN
select(col(SomeNumber))runs on columnsstation(str),bears(i64) andweight(f64) - THEN the result has columns
bearsandweight
- WHEN
select(col(float, string))runs on the same frame - THEN the result has columns
stationandweight
- WHEN
col(seq[int])is compiled - THEN compilation fails
Selecting by name
col(a, b, ...) with two or more names, and col(names) with an openArray[string], SHALL return a Selector for those columns in that order, and all() SHALL select every column. col with one name SHALL keep returning an Expr, and a name that starts with ^ and ends with $ SHALL be a regex.
let df = newDataFrame(series("weight_kg", [410.5]), series("weight_lb", [905.0]),
series("name", ["Nanuq"]))
echo df.select(col("^weight_.*$")).columns # regex
echo df.select(col("name", "weight_kg")).columns
echo df.select(all()).columns
let wanted = @["weight_lb", "name"]
echo df.select(col(wanted)).columns
@["weight_kg", "weight_lb"]
@["name", "weight_kg"]
@["weight_kg", "weight_lb", "name"]
@["weight_lb", "name"]
- WHEN
select(col("^weight_.*$"))runs on columnsweight_kg,weight_lbandname - THEN the result has columns
weight_kgandweight_lb
- WHEN
select(col(@["c", "a"]))runs on columnsa,bandc - THEN the result has columns
canda
Excluding columns
Selector SHALL support exclude(names: varargs[string]), which removes the named columns from the selection.
let df = newDataFrame(series("id", [1]), series("a", [2]), series("b", [3]))
echo df.select(all().exclude("id")).columns
@["a", "b"]
- WHEN
select(all().exclude("id"))runs on columnsid,aandb - THEN the result has columns
aandb
Selectors as expressions
A Selector SHALL convert to Expr automatically. An expression built from it SHALL apply to every selected column and keep each column's name.
let df = newDataFrame(series("station", ["N", "N", "S"]), series("bears", [3, 5, 4]),
series("cubs", [1, 0, 2]), series("weight", [410.5, 380.0, 300.0]))
echo df.lazy.groupBy(col("station"))
.agg(col(SomeNumber).exclude("cubs").mean)
.sort("station").collect
shape: (2, 3)
┌─────────┬───────┬────────┐
│ station ┆ bears ┆ weight │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞═════════╪═══════╪════════╡
│ N ┆ 4.0 ┆ 395.25 │
│ S ┆ 4.0 ┆ 300.0 │
└─────────┴───────┴────────┘
- WHEN a frame is grouped by
stationand aggregated withcol(SomeNumber).exclude("cubs").mean - THEN the result has
stationand one mean column per remaining numeric column, with the original names
Output name suffix and prefix
Expr SHALL support name.suffix(s) and name.prefix(s), which append or prepend s to the name of every column the expression produces.
let df = newDataFrame(series("a", [1.0, 3.0]), series("b", [2.0, 4.0]))
echo df.select(col(SomeFloat).mean.name.suffix("_mean"),
col(SomeFloat).max.name.prefix("max_"))
shape: (1, 4)
┌────────┬────────┬───────┬───────┐
│ a_mean ┆ b_mean ┆ max_a ┆ max_b │
│ --- ┆ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ f64 ┆ f64 │
╞════════╪════════╪═══════╪═══════╡
│ 2.0 ┆ 3.0 ┆ 3.0 ┆ 4.0 │
└────────┴────────┴───────┴───────┘
- WHEN
agg(col(SomeFloat).mean.name.suffix("_mean"), col(SomeFloat).max.name.suffix("_max"))runs on float columnsaandb - THEN the result has columns
a_mean,b_mean,a_maxandb_max
Operators on selectors
Arithmetic, comparison and logical operators SHALL accept a selector (all(), col("a", "b"), col(SomeNumber)) on either side, applying to each selected column and keeping its name; a comparison with a value on the left SHALL be mirrored (0 < x is x > 0), so the result keeps the column's name.
let df = newDataFrame(series("a", @[1, -1]), series("b", @[0, 2]))
echo df.select((all() > 0).name.suffix(" > 0"))
echo df.select(0 < col("a"))
shape: (2, 2)
┌───────┬───────┐
│ a > 0 ┆ b > 0 │
│ --- ┆ --- │
│ bool ┆ bool │
╞═══════╪═══════╡
│ true ┆ false │
│ false ┆ true │
└───────┴───────┘
shape: (2, 1)
┌───────┐
│ a │
│ --- │
│ bool │
╞═══════╡
│ true │
│ false │
└───────┘
- WHEN
all() * 2is selected - THEN every column is doubled and keeps its name
combining-frames
Purpose: How Nanuq combines frames: joins of two frames on keys (or a cross join), and concatenation of several frames vertically, horizontally or diagonally.
Joins
The API SHALL join two LazyFrames or two DataFrames with join, with how one of a JoinType: Inner (default), Left, Right, Full, Semi, Anti or Cross. Keys SHALL be given as on (same names on both sides) or leftOn and rightOn, as column names or expressions. A cross join SHALL take no keys.
let bears = newDataFrame(series("k", [1, 2, 3]), series("bear", ["Nanuq", "Ursa", "Kuma"]))
let seen = newDataFrame(series("k", [1, 3]), series("where", ["ice", "shore"]))
echo bears.join(seen, on = ["k"], how = Left, maintainOrder = Left)
echo bears.join(seen, on = ["k"], how = Anti)
shape: (3, 3)
┌─────┬───────┬───────┐
│ k ┆ bear ┆ where │
│ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str │
╞═════╪═══════╪═══════╡
│ 1 ┆ Nanuq ┆ ice │
│ 2 ┆ Ursa ┆ null │
│ 3 ┆ Kuma ┆ shore │
└─────┴───────┴───────┘
shape: (1, 2)
┌─────┬──────┐
│ k ┆ bear │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪══════╡
│ 2 ┆ Ursa │
└─────┴──────┘
- WHEN a frame with keys 1, 2, 3 is left-joined on
kto a frame with keys 1, 3 - THEN the result has three rows, and the right side's columns are null for key 2
- WHEN the same frames are semi-joined and anti-joined
- THEN the semi join keeps the rows with keys 1 and 3, and the anti join keeps the row with key 2, with only the left columns
- WHEN frames are joined with
leftOn = ["id"]andrightOn = ["station_id"] - THEN rows are matched on those columns
- WHEN a 2-row frame is joined to a 3-row frame with
how = Cross - THEN the result has 6 rows
- WHEN
joinis called without keys and a join type other thanCross - THEN
PolarsErroris raised
Join options
join SHALL accept, with Polars' defaults: suffix ("_right") for clashing column names, validate (JoinValidation: ManyToMany, or ManyToOne, OneToMany, OneToOne), nullsEqual (false), coalesce (none(bool) for Polars' per-join-type default) and maintainOrder (MaintainOrderJoin: None, or Left, Right, LeftRight, RightLeft).
let a = newDataFrame(series("k", [1, 2]), series("v", [10, 20]))
let b = newDataFrame(series("k", [1, 2]), series("v", [100, 200]))
echo a.join(b, on = ["k"], suffix = "_b", validate = OneToOne, maintainOrder = Left)
shape: (2, 3)
┌─────┬─────┬─────┐
│ k ┆ v ┆ v_b │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1 ┆ 10 ┆ 100 │
│ 2 ┆ 20 ┆ 200 │
└─────┴─────┴─────┘
- WHEN both frames have a non-key column
vandsuffix = "_b" - THEN the result has columns
vandv_b
- WHEN the right frame has a duplicate key and
validate = ManyToOne - THEN
PolarsErroris raised when the query runs
- WHEN both frames have a null key, joined with
nullsEqual = true - THEN the null keys match each other; with the default they don't
- WHEN a left join runs with
maintainOrder = Left - THEN the result rows follow the left frame's order
Concatenation
The API SHALL concatenate a list of LazyFrames or DataFrames with concat, with how a ConcatMethod: Vertical (default, same schema), VerticalRelaxed (cast to common supertypes), Horizontal (side by side), Diagonal (union of columns, missing ones null) or DiagonalRelaxed. An empty list SHALL raise PolarsError.
let ab = newDataFrame(series("a", [1]), series("b", [2]))
let bc = newDataFrame(series("b", [3]), series("c", [4]))
echo concat([ab, bc], how = Diagonal)
shape: (2, 3)
┌──────┬─────┬──────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞══════╪═════╪══════╡
│ 1 ┆ 2 ┆ null │
│ null ┆ 3 ┆ 4 │
└──────┴─────┴──────┘
- WHEN two frames with the same columns and 2 and 3 rows are concatenated
- THEN the result has 5 rows in input order
- WHEN frames whose column
ais i64 in one and f64 in the other are concatenated - THEN
VerticalraisesPolarsErrorandVerticalRelaxedreturnsaas f64
- WHEN a frame with columns
a, band one withb, care concatenated diagonally - THEN the result has columns
a, b, c, with nulls where a frame had no column
- WHEN a frame with column
aand one with columnbare concatenated horizontally - THEN the result has columns
aandb
csv-io
Purpose: Reading and writing CSV files: lazy scans of a file or a glob, eager reads, and the named read and write options, following Polars' names and defaults.
Scanning CSV
The API SHALL provide scanCsv(path, ...), which returns a LazyFrame without reading the file until the query runs. path SHALL accept a glob that matches several files with the same columns. A glob whose files have different columns SHALL raise PolarsError when the query runs.
let dir = getTempDir() / "census"
createDir dir
writeFile(dir / "week_01.csv", "station,bears\nNorth,3\nSouth,5\n")
writeFile(dir / "week_02.csv", "station,bears\nNorth,4\nSouth,2\nEast,1\n")
let weeks = scanCsv(dir / "*.csv") # nothing is read yet
echo weeks.groupBy(col("station")).agg(col("bears").sum).sort("station").collect
shape: (3, 2)
┌─────────┬───────┐
│ station ┆ bears │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════════╪═══════╡
│ East ┆ 1 │
│ North ┆ 7 │
│ South ┆ 7 │
└─────────┴───────┘
- WHEN
scanCsv(dir / "*.csv").collectruns on two files with the same columns and 2 and 3 rows - THEN the result has 5 rows
CSV read options
readCsv and scanCsv SHALL take these named options with Polars' defaults:
separator = ','andhasHeader = truenullValuesandschemaOverrides((string, DataType)pairs)skipRows = 0,nRows = none(int)andcolumns(all when empty)inferSchemaLength = some(100), wherenonescans all rowsignoreErrors = falseanddecimalComma = falsetryParseDates = false, which reads ISO dates, datetimes and times as temporal columns
nRows and inferSchemaLength SHALL also accept a plain int.
let path = getTempDir() / "survey.csv"
writeFile(path, "Polar survey 2026\nexported by hand\nstation;bears;weight\n" &
"North;3;410\nSouth;lots;380\nEast;1;355\n")
echo readCsv(path, separator = ';', skipRows = 2, nRows = 2, nullValues = ["lots"],
schemaOverrides = {"weight": Float64}, columns = ["station", "weight", "bears"])
let stages = getTempDir() / "stages.csv"
writeFile(stages, "stage,day,start\n1,2026-07-04,13:10:00\n2,2026-07-05,12:45:00\n")
echo readCsv(stages, tryParseDates = true).schema
shape: (2, 3)
┌─────────┬────────┬───────┐
│ station ┆ weight ┆ bears │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ i64 │
╞═════════╪════════╪═══════╡
│ North ┆ 410.0 ┆ 3 │
│ South ┆ 380.0 ┆ null │
└─────────┴────────┴───────┘
{"stage": Int64, "day": Date, "start": TimeOfDay}
- WHEN a file with
;separators and the value "lots" is read withseparator = ';', nullValues = ["lots"] - THEN the columns are split at
;and "lots" is null
- WHEN a column of whole numbers is read with
schemaOverrides = {"n": Float64} - THEN
dtype("n") == Float64
- WHEN a file with two preamble lines and 10 data rows is read with
skipRows = 2, nRows = 3 - THEN the header is the third line and the result has 3 rows
- WHEN a file with columns
a,bandcis read withcolumns = ["c", "a"] - THEN the result has columns
canda
- WHEN a column of ISO dates is read with and without
tryParseDates = true - THEN its dtype is
DateandString
CSV write options
writeCsv(df, path, ...) SHALL take these named options:
separator = ','andincludeHeader = truenullValue = ""quoteStyle = Necessary, a pure enumQuoteStyle(Necessary,Always,NonNumeric,Never)floatPrecision = none(int)(also a plainint)decimalComma = false
let df = newDataFrame(series("bear", ["Nanuq", "Ursa"]),
series("weight", [some(410.256), none(float)]))
let path = getTempDir() / "out.csv"
df.writeCsv(path, separator = ';', nullValue = "NA", floatPrecision = 1,
decimalComma = true, quoteStyle = NonNumeric)
echo readFile(path)
"bear";"weight"
"Nanuq";410,3
"Ursa";NA
- WHEN a frame with 1.5 is written with
separator = ';', decimalComma = trueand read back with the same options - THEN the file holds
1,5and the value read back is 1.5
- WHEN a frame is written with
quoteStyle = Always - THEN every field in the file is quoted
- WHEN a frame with a null and 3.14159 is written with
nullValue = "NA", floatPrecision = 2 - THEN the file holds
NAand3.14
Reading CSV from a stream
readCsv SHALL also take a Nim Stream instead of a path, read all of it when called, and take every CSV read option.
import std/streams
let text = "station;bears\nNorth;3\nSouth;NA\n"
echo readCsv(newStringStream(text), separator = ';', nullValues = ["NA"])
shape: (2, 2)
┌─────────┬───────┐
│ station ┆ bears │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════════╪═══════╡
│ North ┆ 3 │
│ South ┆ null │
└─────────┴───────┘
- WHEN CSV text with
;separators and "NA" is read from a stream withseparator = ';', nullValues = ["NA"] - THEN the result equals reading the same text from a file with those options
- WHEN an empty stream is read
- THEN
NoDataErroris raised
Quoting, encoding and new column names
readCsv and scanCsv SHALL take quoteChar = some('"') (none(char) turns quoting off), encoding = CsvEncoding.Utf8 (Utf8Lossy replaces invalid UTF-8 instead of raising) and newColumns, which renames the first columns.
import std/os
let path = getTempDir() / "lines.txt"
writeFile(path, "a \"quoted, line\nplain\n")
echo readCsv(path, separator = '\x01', hasHeader = false, quoteChar = none(char),
newColumns = ["line"])
shape: (2, 1)
┌─────────────────┐
│ line │
│ --- │
│ str │
╞═════════════════╡
│ a "quoted, line │
│ plain │
└─────────────────┘
- WHEN a line holds the byte 0xFF and
encoding = CsvEncoding.Utf8Lossy - THEN the line is read, with a replacement character
Comment lines
readCsv and scanCsv SHALL skip lines starting with commentPrefix (none when empty).
import std/streams
echo readCsv(newStringStream("# measured 2026\nbear,kg\nAda,410\n"), commentPrefix = "#")
shape: (1, 2)
┌──────┬─────┐
│ bear ┆ kg │
│ --- ┆ --- │
│ str ┆ i64 │
╞══════╪═════╡
│ Ada ┆ 410 │
└──────┴─────┘
- WHEN a CSV starting with "# note" is read without
commentPrefix - THEN "# note" is the first column name
cumulative-functions
Purpose: Functions that compare each row with the rows before it: shifting, differences, relative change, running totals and records, run ids and peaks.
Shifting
e.shift(n = 1) SHALL move values down by n rows (up when n is negative), filling the rows left empty with null, or with fillValue when it is given. Inside over, the shift SHALL happen within each group.
let df = newDataFrame:
month: ["Jan", "Feb", "Mar", "Apr"]
anomaly: [0.5, 0.8, 1.2, 0.9]
echo df.withColumns(col.anomaly.shift.alias("before"),
col.anomaly.shift(-1, fillValue = 0.0).alias("after"))
shape: (4, 4)
┌───────┬─────────┬────────┬───────┐
│ month ┆ anomaly ┆ before ┆ after │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 │
╞═══════╪═════════╪════════╪═══════╡
│ Jan ┆ 0.5 ┆ null ┆ 0.8 │
│ Feb ┆ 0.8 ┆ 0.5 ┆ 1.2 │
│ Mar ┆ 1.2 ┆ 0.8 ┆ 0.9 │
│ Apr ┆ 0.9 ┆ 1.2 ┆ 0.0 │
└───────┴─────────┴────────┴───────┘
- WHEN
col.x.shift.over(col.g)runs on groups a = 1, 2 and b = 3, 4 - THEN the result is null, 1, null, 3
Differences
e.diff(n = 1, nullBehavior = NullBehavior.Ignore) SHALL subtract from each value the value n rows above, with null where there is none; NullBehavior.Drop SHALL leave out those rows. e.pctChange(n = 1) SHALL return the relative change from the value n rows above.
let df = newDataFrame:
year: [2021, 2022, 2023, 2024]
temp: [14.8, 14.9, 15.1, 15.3]
echo df.select(col.year, col.temp.diff.round(2).alias("diff"),
col.temp.pctChange.round(4).alias("pct"))
shape: (4, 3)
┌──────┬──────┬────────┐
│ year ┆ diff ┆ pct │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 │
╞══════╪══════╪════════╡
│ 2021 ┆ null ┆ null │
│ 2022 ┆ 0.1 ┆ 0.0068 │
│ 2023 ┆ 0.2 ┆ 0.0134 │
│ 2024 ┆ 0.2 ┆ 0.0132 │
└──────┴──────┴────────┘
- WHEN
diff(nullBehavior = Drop)runs on 1, 4, 9 - THEN the result is 3, 5
Cumulative functions
cumSum, cumProd, cumMin, cumMax and cumCount SHALL return the running sum, product, minimum, maximum and count of non-null values from the first row, or from the last row with reverse = true.
let df = newDataFrame:
rain: [3, 0, 7, 2]
echo df.withColumns(col.rain.cumSum.alias("total"), col.rain.cumMax.alias("wettest"),
col.rain.cumSum(reverse = true).alias("still_to_come"))
shape: (4, 4)
┌──────┬───────┬─────────┬───────────────┐
│ rain ┆ total ┆ wettest ┆ still_to_come │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 │
╞══════╪═══════╪═════════╪═══════════════╡
│ 3 ┆ 3 ┆ 3 ┆ 12 │
│ 0 ┆ 3 ┆ 3 ┆ 9 │
│ 7 ┆ 10 ┆ 7 ┆ 9 │
│ 2 ┆ 12 ┆ 7 ┆ 2 │
└──────┴───────┴─────────┴───────────────┘
- WHEN
cumMaxruns on 3, 1, 5, 2 - THEN the result is 3, 3, 5, 5
- WHEN
cumCountruns on 1, null, 3 - THEN the result is 1, 1, 2
Runs and peaks
e.rleId SHALL number the runs of equal consecutive values, starting at 0 and growing by one each time the value changes. peakMax and peakMin SHALL be true at local maxima and minima.
let df = newDataFrame:
season: ["DJF", "JFM", "FMA", "MAM", "AMJ", "MJJ"]
warm: [true, true, false, false, true, true]
echo df.withColumns(col.warm.rleId.alias("run"))
shape: (6, 3)
┌────────┬───────┬─────┐
│ season ┆ warm ┆ run │
│ --- ┆ --- ┆ --- │
│ str ┆ bool ┆ u32 │
╞════════╪═══════╪═════╡
│ DJF ┆ true ┆ 0 │
│ JFM ┆ true ┆ 0 │
│ FMA ┆ false ┆ 1 │
│ MAM ┆ false ┆ 1 │
│ AMJ ┆ true ┆ 2 │
│ MJJ ┆ true ┆ 2 │
└────────┴───────┴─────┘
- WHEN rows are grouped by
rleIdof true, true, false, true and counted - THEN the runs have lengths 2, 1 and 1
data-types
Purpose: How Nanuq represents Polars data types in Nim (DataType), reads schemas, and casts
columns and expressions.
DataType values
The API SHALL provide a DataType value with a kind of type DataTypeKind (a pure enum, see api-conventions) covering Boolean, Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64, String, Null, Date, Datetime, Duration, Time, Categorical and Enum, plus DataTypeKind.Other carrying Polars' name for any other dtype. Datetime and Duration values SHALL carry a timeUnit (std/times' TimeUnit: Nanoseconds, Microseconds or Milliseconds), Datetime values a timeZone ("" when naive), and Enum values their categories. dtype(df, col) SHALL return a DataType. dtype == T with a Nim type SHALL compare with dataType(T), except that DateTime and Duration SHALL match any time unit and zone. $ SHALL print a data type as the Nanuq code that builds or names it: the constant (Int64), the constructor (Enum(["low", "high"])), or for temporal types the Nim type a column casts to (Date, TimeOfDay, DateTime(Milliseconds, "Europe/Rome"), Duration(Microseconds)). Table headers, glimpse and toHtml SHALL keep Polars' short names (i64).
let df = newDataFrame(series("a", [1, 2]))
echo df.dtype("a") # as Nanuq code
echo df.dtype("a") == Int64
echo df.dtype("a").kind
let t = newDataFrame(series("at", [dateTime(2026, mJul, 4, zone = utc())],
timeUnit = Milliseconds, timeZone = "Europe/Rome"))
echo t.dtype("at"), " ", t.dtype("at").timeZone, " ", t.dtype("at") == DateTime
Int64
true
Int64
DateTime(Milliseconds, "Europe/Rome") Europe/Rome true
- WHEN a DataFrame is built from a Nim
seq[int]columna - THEN
df.dtype("a") == Int64and$df.dtype("a") == "Int64"
- WHEN a column has a dtype Nanuq does not model
- THEN its
kindisDataTypeKind.Otherand$returns Polars' name for it
- WHEN a Datetime column has unit ms and zone Europe/Rome
- THEN
$givesDateTime(Milliseconds, "Europe/Rome")and it equalsDateTime
- WHEN a column is cast to
Enum(["low", "high"]) - THEN
$of its dtype givesEnum(["low", "high"])andcategoriesis@["low", "high"]
- WHEN a frame with an Int64 column is printed or turned into HTML
- THEN the column header shows
i64
DataType constants and predicates
The API SHALL export DataType constants with Polars' names (Int64, String, ...), ==, $ printing the constant's name, and the predicates isInteger, isSignedInteger, isUnsignedInteger, isFloat and isNumeric.
echo UInt8.isNumeric, " ", Float32.isFloat, " ", String.isNumeric
true true false
- WHEN
isNumericis called onUInt8,Float32andString - THEN it returns true, true and false
Schemas
The API SHALL return the column names and dtypes of a DataFrame (schema) and of a LazyFrame without collecting it (collectSchema) as a Schema, an OrderedTable[string, DataType] in column order, and the dtypes alone with dtypes.
let df = newDataFrame(series("a", [1, 2]), series("b", ["x", "y"]))
echo df.schema
echo df.lazy.withColumns((col("a") * 1.5).alias("c")).collectSchema # nothing runs
{"a": Int64, "b": String}
{"a": Int64, "b": String, "c": Float64}
- WHEN
schemais called on a DataFrame with columnsa(i64) andb(str) - THEN the keys are
a,bin that order and the values areInt64,String
- WHEN
collectSchemais called on a LazyFrame that adds(col("a") * 1.5).alias("c") - THEN the schema has
cwithFloat64, and the query is not executed
Casting
The API SHALL cast expressions (e.cast(target, strict = true)), all columns of a DataFrame or LazyFrame (cast(target, strict = true)), where target is a Nim type or a DataType, and named columns (cast({"a": Int32}, strict = true)) with DataType values. Temporal Nim targets (Date, DateTime, Duration, TimeOfDay) SHALL take timeUnit = Microseconds and, for DateTime, timeZone = "". A strict cast SHALL raise PolarsError (when the query runs) if a value cannot be converted; a non-strict cast SHALL turn such values into nulls. Casting to a DataTypeKind.Other dtype SHALL raise PolarsError.
let df = newDataFrame(series("a", [1, 2]), series("s", ["1", "x"]))
echo df.cast({"a": Int32}).dtype("a")
echo df.select(col("a").cast(float32)).dtype("a")
echo df.select(col("s").cast(Int64, strict = false))
echo df.select(col("a").cast(DateTime, timeUnit = Milliseconds, timeZone = "UTC")).dtype("a")
Int32
Float32
shape: (2, 1)
┌──────┐
│ s │
│ --- │
│ i64 │
╞══════╡
│ 1 │
│ null │
└──────┘
DateTime(Milliseconds, "UTC")
- WHEN
df.cast({"a": Int32})runs on an i64 column - THEN
dtype("a") == Int32andtoList(df, "a", int)returns the same values
- WHEN
col("a").cast(float32)is selected from an i64 column - THEN the result column has dtype
Float32
- WHEN a string column holding "1" and "x" is cast to
Int64withstrict = true - THEN
PolarsErroris raised
- WHEN the same column is cast with
strict = false - THEN the result is 1 and null
- WHEN a column of microseconds
[0, 86_400_000_000]is cast toDateTimeand then toDate - THEN the result is 1970-01-01 and 1970-01-02
Nim types map to DataType
dataType(T) SHALL map int8 to int64, uint8 to uint64, float32, float64, bool and string to their dtypes, int to Int64 and float to Float64. dataType(T, timeUnit = Microseconds, timeZone = "") SHALL map Date, DateTime, std/times' Duration and TimeOfDay to Date, Datetime, Duration and Time. A Nim enum SHALL map to an Enum of $ of its values. seq[T] SHALL map to a List, array[N, T] to an Array and objects and named tuples to a Struct of their fields, at any depth. Other types SHALL not compile.
type Medal = enum Gold, Silver, Bronze
echo dataType(int), " ", dataType(float32), " ", dataType(uint8), " ", dataType(string)
echo dataType(Date), " ", dataType(DateTime), " ", dataType(Duration, Nanoseconds), " ", dataType(TimeOfDay)
echo dataType(Medal), " ", dataType(Medal).categories
echo dataType(seq[string]), " ", dataType(array[3, float]), " ", dataType(tuple[x: int, tags: seq[string]]).fields
Int64 Float32 UInt8 String
Date DateTime(Microseconds) Duration(Nanoseconds) TimeOfDay
Enum(["Gold", "Silver", "Bronze"]) @["Gold", "Silver", "Bronze"]
List(String) Array(Float64, 3) @[(name: "x", dtype: Int64), (name: "tags", dtype: List(String))]
- WHEN
dataType(int)is evaluated - THEN it equals
Int64, the dtypeseriesbuilds fromseq[int]
- WHEN
col("a").cast(ref int)is compiled - THEN compilation fails
- WHEN
dataType(DateTime, Seconds)is evaluated - THEN
ValueErroris raised
- WHEN
dataType(Medal)is evaluated forenum Gold, Silver, Bronze - THEN it equals
Enum(["Gold", "Silver", "Bronze"])
- WHEN
dataType(seq[seq[int]])is evaluated - THEN it equals
List(List(Int64))
Full-range UInt64
UInt64 columns SHALL keep all 64 bits between Nim and Polars: series(name, seq[uint64]) (with or without Option) and toList(uint64) SHALL handle values above high(int64).
let df = newDataFrame(series("key", @[1'u64, 9223372036854775809'u64]))
echo df.toList("key", uint64)
echo df.select(col("key").bitwiseXor)
@[1, 9223372036854775809]
shape: (1, 1)
┌─────────────────────┐
│ key │
│ --- │
│ u64 │
╞═════════════════════╡
│ 9223372036854775808 │
└─────────────────────┘
- WHEN
series("u", [some(x), none(uint64)])is built - THEN the second value is null
database-io
Purpose: Reading query results from SQLite and writing frames to it, in the optional module nanuq/database (on db_connector).
Writing to a database
writeDatabase(df, tableName, connection, ifTableExists = IfTableExists.Fail) in nanuq/database SHALL write the frame's rows to a SQLite table, creating it with column types from the frame (integers and booleans INTEGER, floats REAL, Binary BLOB, the rest TEXT), and return the number of rows written. An existing table SHALL raise ValueError with Fail, be dropped first with Replace, and receive the rows with Append.
import nanuq/database, db_connector/db_sqlite
let db = open(":memory:", "", "", "")
let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380]))
echo df.writeDatabase("bears", db)
echo df.writeDatabase("bears", db, IfTableExists.Append)
2
2
- WHEN a frame is written to an existing table with
IfTableExists.Fail - THEN
ValueErroris raised and the table is unchanged
Reading from a database
readDatabase(query, connection, schemaOverrides = []) SHALL run a query on an open SQLite connection and return its rows, with INTEGER values as Int64, REAL (or mixed numbers) as Float64, TEXT as String and BLOB as Binary, and a column of only nulls typed from its declared type. readDatabaseUri(query, "sqlite:///path") SHALL open the database for the query and close it.
import nanuq/database, db_connector/db_sqlite
let db = open(":memory:", "", "", "")
discard newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.5, 380.0])).writeDatabase("bears", db)
echo readDatabase("select bear, kg * 2 as double from bears where kg > 400", db)
shape: (1, 2)
┌──────┬────────┐
│ bear ┆ double │
│ --- ┆ --- │
│ str ┆ f64 │
╞══════╪════════╡
│ Ada ┆ 821.0 │
└──────┴────────┘
- WHEN the query names a table that does not exist
- THEN
IOErroris raised
- WHEN
readDatabaseUrigets apostgres://URI - THEN
ValueErroris raised
dataframe-api
Purpose: The Nim-facing API in src/nanuq.nim: DataFrame, LazyFrame and Expr values backed by
Polars, with automatic memory management and Nim exceptions.
Automatic memory management
DataFrame, LazyFrame, Expr and Series SHALL be Nim ref types whose destructors free the underlying Rust object when the last reference goes away. Copying the inner objects SHALL be a compile-time error.
var a = newDataFrame(series("n", [1, 2]))
let b = a # same Polars frame, no copy
a = nil # still alive through b
echo b.shape # freed when b goes out of scope
(2, 1)
- WHEN two Nim variables refer to the same DataFrame
- THEN the Rust object is freed once, after both go out of scope
Building and reading data
The API SHALL build a DataFrame from Nim arrays of int, float, bool and string (series, newDataFrame), read and write CSV with a header row, and expose shape, columns, dtype, head, $ (Polars' table format), single cells and whole columns (toList).
let df = newDataFrame(series("bear", ["Nanuq", "Ursa"]), series("weight", [410.5, 380.0]))
echo df
echo df.shape, " ", df.columns, " ", df["bear", 0, string], " ", df.toList("weight", float)
shape: (2, 2)
┌───────┬────────┐
│ bear ┆ weight │
│ --- ┆ --- │
│ str ┆ f64 │
╞═══════╪════════╡
│ Nanuq ┆ 410.5 │
│ Ursa ┆ 380.0 │
└───────┴────────┘
(2, 2) @["bear", "weight"] Nanuq @[410.5, 380.0]
- WHEN
newDataFramegets series of different lengths - THEN
PolarsErroris raised
- WHEN a module imports
nanuqandstd/[os, sequtils]and callstoSeq(walkFiles("*.csv")) - THEN it compiles and returns the matching paths
Reading columns by type
Reading as float SHALL accept any integer or float column; as string, any column, formatted as Polars does; as int, only integer columns; as bool, only boolean columns. A dtype that does not match SHALL raise PolarsError.
let df = newDataFrame(series("a", [1, 2]))
echo df.toList("a", float) # integers widen to float
echo df.toList("a", string) # any column formats as text
@[1.0, 2.0]
@["1", "2"]
- WHEN an i64 column holding 1, 2 is read with
toList(df, "a", float) - THEN the result is
@[1.0, 2.0]
- WHEN an f64 column is read with
toList(df, "a", int) - THEN
PolarsErroris raised
- WHEN a bool column is read with
toList(df, "d", bool) - THEN the result holds the column's values
Expressions and lazy queries
The API SHALL provide col, lit, arithmetic, comparison and boolean operators on Expr (lifting Nim literals automatically), the aggregations sum, mean, min, max, count, first, last, nUnique and std, and alias. LazyFrame SHALL support select, withColumns, filter, groupBy/agg, sort, limit, explain and collect. select and groupBy SHALL take expressions or column names (select("a", "b"), groupBy("species")); groupBy SHALL keep the groups in the order their keys first appear (Python's maintain_order=True, always on). On a DataFrame, groupBy, groupByDynamic and rolling followed by agg SHALL return a DataFrame, as in Python; on a LazyFrame they return a LazyFrame. DataFrame SHALL offer eager shortcuts for select, withColumns, filter and sort.
let query = penguins().lazy
.filter(col("body_mass_g").isNotNull)
.groupBy(col("species"))
.agg(col("body_mass_g").mean.alias("mass"), col("species").count.alias("n"))
.sort("mass", descending = true)
echo query.collect # nothing runs before collect
shape: (3, 3)
┌───────────┬─────────────┬─────┐
│ species ┆ mass ┆ n │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ u32 │
╞═══════════╪═════════════╪═════╡
│ Gentoo ┆ 5076.01626 ┆ 123 │
│ Chinstrap ┆ 3733.088235 ┆ 68 │
│ Adelie ┆ 3700.662252 ┆ 151 │
└───────────┴─────────────┴─────┘
- WHEN
df.groupBy("a").agg(col.v.sum)runs on a DataFrame - THEN the result is a DataFrame, with no
collectneeded
- WHEN
df.select("c", "a")runs - THEN the result has columns c and a, in that order
- WHEN
df.groupBy("a", "b")is followed byagg - THEN it groups as
df.groupBy(col.a, col.b)does
- WHEN a frame with keys b, a, b, c is grouped by the key
- THEN the groups come out as b, a, c
- WHEN a LazyFrame is filtered, grouped, aggregated and sorted
- THEN nothing runs until
collect, which returns the resulting DataFrame
HTML tables
toHtml(df, maxRows = 10, maxCols = 75) SHALL return the HTML that Python Polars' DataFrame._repr_html_ returns for the same data and limits: shape line, names and dtypes header rows, cells formatted by Polars, and … rows and columns when truncated.
- WHEN
toHtmlis called onpenguins() - THEN the result equals what Python Polars'
_repr_html_returns for the same CSV read withnull_values="NA"
- WHEN a DataFrame with 344 rows is rendered with
maxRows = 10 - THEN the body shows rows 0 to 4, a
…row, and rows 339 to 343
- WHEN a string cell holds
<b>and another cell is null - THEN the first is shown as
"<b>"and the second asnull
Block syntax for building a DataFrame
newDataFrame SHALL accept a block of name: [values] lines and build one column per line, in order, as series(name, values) would. A name SHALL be a Nim identifier or a string literal. A nil inside the brackets SHALL be a missing value, and the column SHALL then have the type of its other values. newDataFrame SHALL keep accepting series (newDataFrame(series(...), ...), a seq of series, or none at all).
let df = newDataFrame:
rider: ["Pogačar", "Seixas", "Vingegaard"]
wins: [22, 8, nil]
"win %": [0.31, 0.12, 0.05]
echo df
shape: (3, 3)
┌────────────┬──────┬───────┐
│ rider ┆ wins ┆ win % │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ f64 │
╞════════════╪══════╪═══════╡
│ Pogačar ┆ 22 ┆ 0.31 │
│ Seixas ┆ 8 ┆ 0.12 │
│ Vingegaard ┆ null ┆ 0.05 │
└────────────┴──────┴───────┘
- WHEN a frame is built with the block syntax and the same frame with
seriescalls - THEN both have the same columns, dtypes and values
- WHEN a line reads
wins: [22, nil] - THEN column "wins" is i64 with values 22 and null
- WHEN a line reads
wins: [nil, nil] - THEN the program fails to compile
- WHEN
newDataFrame()is called - THEN the result has shape (0, 0)
Column shorthand
col.name SHALL be the same expression as col("name") for any column name that is a Nim identifier and not taken by Nim first (type, and generic system procs such as repr). Every other form of col SHALL keep working: col("a"), col("a", "b"), col(SomeNumber) and col(float, int). User code SHALL need no pragma to use them.
let df = newDataFrame:
race: ["Sanremo", "Lombardia"]
"end": [1, 2]
echo df.select(col.race, col.end, col("race", "end").count.name.suffix("_n"))
shape: (2, 4)
┌───────────┬─────┬────────┬───────┐
│ race ┆ end ┆ race_n ┆ end_n │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ u32 ┆ u32 │
╞═══════════╪═════╪════════╪═══════╡
│ Sanremo ┆ 1 ┆ 2 ┆ 2 │
│ Lombardia ┆ 2 ┆ 2 ┆ 2 │
└───────────┴─────┴────────┴───────┘
- WHEN
$col.raceand$col("race")are compared - THEN they are equal
- WHEN
col.lenandcol.minare used - THEN they select the columns "len" and "min"
True division
/ on expressions SHALL be Polars' true division: the result SHALL be a float column even when both sides are integers, and a division by zero SHALL give inf or NaN, not null. div SHALL stay floor division.
let df = newDataFrame:
seconds: [7200, 5400, 0]
echo df.select(col.seconds, (col.seconds / 3600).alias("hours"),
(col.seconds div 3600).alias("whole"), (col.seconds / 0).alias("by_zero"))
shape: (3, 4)
┌─────────┬───────┬───────┬─────────┐
│ seconds ┆ hours ┆ whole ┆ by_zero │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ i64 ┆ f64 │
╞═════════╪═══════╪═══════╪═════════╡
│ 7200 ┆ 2.0 ┆ 2 ┆ inf │
│ 5400 ┆ 1.5 ┆ 1 ┆ inf │
│ 0 ┆ 0.0 ┆ 0 ┆ NaN │
└─────────┴───────┴───────┴─────────┘
- WHEN
lit(7) / 2is evaluated - THEN the result is 3.5 with dtype f64
- WHEN
lit(7) div 2is evaluated - THEN the result is 3 with dtype i64
Errors as PolarsError
Any failing FFI call SHALL raise a PolarsError, or Nim's IOError for IO failures, carrying the message from Rust. The type SHALL follow the Rust PolarsError variant: ColumnNotFoundError, ComputeError, DuplicateError, InvalidOperationError, NoDataError, OutOfBoundsError, SchemaError, SchemaFieldNotFoundError, ShapeError, StructFieldNotFoundError and SqlError, all subtypes of PolarsError.
let df = newDataFrame(series("a", [1]), series("s", ["x"]))
try:
discard df.select(col("nope"))
except ColumnNotFoundError as e:
echo e.msg.splitLines[0]
try:
discard df.select(col("s").cast(int))
except PolarsError as e:
echo e.name
try:
discard readCsv("no/such/file.csv")
except IOError:
echo "IOError"
not found: unable to find column "nope"; valid columns: ["a", "s"]
InvalidOperationError
IOError
- WHEN a query selects a column that does not exist
- THEN
ColumnNotFoundErroris raised with the Polars error message
- WHEN a strict cast fails and the code catches
PolarsError - THEN the handler runs, with an
InvalidOperationError
- WHEN
readCsvgets a path that does not exist - THEN
IOErroris raised, and it is not aPolarsError
datamancer-interop
Purpose: Converting DataFrames between Nanuq and Datamancer (nanuq/datamancer), so Datamancer
and ggplotnim code can use Polars for queries. Datamancer stays an optional dependency.
To Datamancer
toDatamancer SHALL copy every column, in order and with its name, into a Datamancer DataFrame: integers as int, floats as float, booleans as bool, strings as string, and any other dtype as string formatted by Polars.
import nanuq/datamancer
let dm = penguins().dropNulls.toDatamancer # a Datamancer DataFrame
echo dm.len
333
- WHEN
penguins().dropNulls().toDatamanceris called - THEN the result has 333 rows, the same column names in order, and
body_mass_gis anintcolumn
Nulls to Datamancer
A column with nulls SHALL become an object column whose missing entries are Datamancer null values and whose other entries hold the values.
- WHEN
penguins().toDatamanceris called - THEN
body_mass_gis an object column with 2nullvalues, anddrop_nullon it leaves 342 rows
From Datamancer
fromDatamancer SHALL copy every column back in order: int to i64, float to f64, bool to bool, string to str, constant columns repeated, and object columns of one value kind plus nulls to that dtype with nulls. Other object columns SHALL raise PolarsError.
import nanuq/datamancer
let back = penguins().toDatamancer.fromDatamancer
echo back.shape, " ", back.nullCount("body_mass_g")
(344, 8) 2
- WHEN a Nanuq DataFrame is converted with
toDatamancerand back withfromDatamancer - THEN it has the same shape, columns, dtypes (for i64, f64, bool, str) and null counts
- WHEN a Datamancer object column holds both an int and a string
- THEN
fromDatamancerraisesPolarsErrornaming the column
Optional dependency
Importing nanuq SHALL NOT require Datamancer; only importing nanuq/datamancer does.
- WHEN a program imports only
nanuqon a machine without Datamancer - THEN it compiles
datasets
Purpose: Small, well-known datasets loadable with one call and no file path, for examples, tests and documentation. They are bundled for convenience during early development and are expected to move out of the library later.
Penguins dataset
nanuq/datasets SHALL provide penguins() returning the palmerpenguins table: 344 rows and the columns species, island, bill_length_mm, bill_depth_mm, flipper_length_mm, body_mass_g, sex and year, with "NA" fields as nulls.
let df = penguins()
echo df.shape
echo df.columns
echo df.nullCount("body_mass_g"), " ", df.nullCount("sex")
(344, 8)
@["species", "island", "bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g", "sex", "year"]
2 11
- WHEN
penguins()is called - THEN the result has shape (344, 8) and the columns listed above, in that order
- WHEN
penguins()is called - THEN
nullCountis 2 for body_mass_g and 11 for sex, and body_mass_g is an integer column
Loading from any working directory
Bundled datasets SHALL load with no path from the caller and without using the network, whatever the program's working directory.
- WHEN a compiled program calls
penguins()from any working directory - THEN the dataset loads
Licensing
Every bundled dataset SHALL ship with its source, credit and license in the repository, and SHALL be under a license that allows redistribution.
- WHEN someone looks for where penguins comes from
- THEN the data folder names palmerpenguins, its authors and CC0
dev-log
Purpose: The Nanuq dev log: dated nimib posts in docs/blog, an index page, and the Nanuq theme
they share. It is published with GitHub Pages and is separate from the official
documentation that will come later.
Index of posts
The site root SHALL be an index page listing every rendered post in docs/blog, newest first, each with its date, title, one-line summary and a link to the post. Adding a post SHALL NOT require editing the index.
- WHEN a post
docs/blog/x.nimwriting2026-11-02-x.htmlis added and CI renders the site - THEN the index lists it first, dated 2 November 2026, with its title and summary
- WHEN a post does not set a summary
- THEN the index still lists it, with date and title only
Dated post files
Each post SHALL render to a file in docs/blog named YYYY-MM-DD-<slug>.html, and its URL SHALL stay the same once published.
- WHEN the index is introduced
- THEN the existing post URLs under
blog/keep working
Polars coverage page
The site SHALL publish a Polars coverage page at polars_coverage.html, linked from the index and the README, rendered from the data file docs/coverage/polars.json. The page SHALL describe the latest Nanuq release only: the data names that release and lists Polars feature groups by area with their Polars names, a status (has it, partly, missing, not planned), a note naming what is still missing, a priority for open groups, and a mark on the groups whose status changed in that release. When the next release has a plan, the data MAY name it and mark the open groups it plans; the page SHALL then show them. The page SHALL show the release totals, counts by area, the open groups by priority and the full catalogue, with the dev log's header and footer. Each release PR SHALL refresh the data for that release. The page is not a dated post and is not listed among the posts.
- WHEN the 0.7 release PR sets the release to 0.7, clears the old new-marks, and updates and marks the rows that 0.7 changed
- THEN the page shows only 0.7 statuses, with the changed groups marked as new in 0.7
- WHEN the data names no next release
- THEN the page shows no Planned column
- WHEN the site is rendered
- THEN the index links to the coverage page, and the page does not appear in the list of posts
OpenSpec page
The site SHALL publish an OpenSpec page at openspec.html, linked from the index, the coverage page and the README's "How development works", rendered by tools/specview.nim with the dev log's header and footer: every change (archived ones hidden until the reader asks for them) and every spec in openspec/specs/ in full. The page is rebuilt from the repository each time the site is, so it shows the specs and changes on main. It is not a dated post and is not listed among the posts.
- WHEN a pull request that archives a change into
openspec/specs/is merged - THEN the published OpenSpec page shows the updated spec and lists the change as archived
- WHEN the site is rendered
- THEN the index links to the OpenSpec page, and the page does not appear in the list of posts
Review mode
Every page rendered with the Nanuq theme SHALL have the review mode of docs/review.nim (from tabelline, until nimib has it), unless the page passes review = false: a version line in the masthead (Version N · updated D, N being the commits that touched the page's source) with ✎ Review, which opens a mode where the reader selects text, comments on it, and exports the comments as Markdown with a YAML block (nimib-review format) naming the page, its source, its version and commit. The page SHALL stay readable at phone width in both modes, light and dark.
- WHEN a reader opens a post on a phone, taps ✎ Review, selects a sentence and writes a note
- THEN the sentence is marked, the note is kept in the browser, and Export gives a text
- naming the post's source (
docs/blog/<post>.nim), its version and the quoted sentence
- WHEN a commit changes a post's source and the site is built again
- THEN the post's version goes up by one, and its comments start empty
Source files
A page that mentions source files of the repository SHALL fold them (whole, or the part it discusses) in a "Source files" section at its end, made with nbSourceFiles and nbFoldCode (from tabelline): each under its path or a title, with its number of lines. The top of the page SHALL point to the section, every file name shown as code in the text SHALL link to its fold, and following such a link SHALL open the fold.
- WHEN a reader taps
ffi.nimin the text of a post - THEN the page goes to the fold of
src/nanuq/ffi.nimin "Source files", opened
excel-io
Purpose: Reading and writing Excel workbooks with pure-Rust crates compiled into the Nanuq library (no Python, no system dependency).
Writing Excel
writeExcel(df, path, worksheet = "Sheet1", includeHeader = true, autofit = false, floatPrecision = none(int)) SHALL write the frame to one worksheet of a new .xlsx file: a header row, then numbers, booleans, dates and datetimes as Excel values and other values as text; nulls SHALL be empty cells.
let path = getTempDir() / "bears.xlsx"
let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.5, 380.0]),
series("seen", @[date(2024, 3, 1), date(2024, 3, 9)]))
df.writeExcel(path, worksheet = "census")
echo fileExists(path)
true
- WHEN the target directory does not exist
- THEN
IOErroris raised
Reading Excel
readExcel(path, sheetName = "", sheetId = 1, hasHeader = true, headerRow = 0, skipRows = 0, columns = [], schemaOverrides = []) SHALL read one sheet (by name, else by position from 1) of an .xlsx, .xlsm, .xlsb, .xls or .ods file. Row headerRow SHALL hold the column names, and skipRows rows SHALL be skipped after it (from the top when hasHeader = false), as Python's default engine (fastexcel) does. Column types SHALL be inferred from the cells: Boolean, Int64 for whole numbers, Float64, Date for dates at midnight, Datetime[ms], else String; schemaOverrides SHALL cast columns and columns keep only those. readExcelSheets(path) SHALL read every sheet into a table by sheet name.
let path = getTempDir() / "bears.xlsx"
newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380]),
series("seen", @[date(2024, 3, 1), date(2024, 3, 9)])).writeExcel(path, worksheet = "census")
echo readExcel(path)
echo readExcel(path, sheetName = "census", skipRows = 1, hasHeader = false)
echo readExcel(path, skipRows = 1)
echo readExcelSheets(path).len
shape: (2, 3)
┌──────┬─────┬────────────┐
│ bear ┆ kg ┆ seen │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ date │
╞══════╪═════╪════════════╡
│ Ada ┆ 410 ┆ 2024-03-01 │
│ Bo ┆ 380 ┆ 2024-03-09 │
└──────┴─────┴────────────┘
shape: (2, 3)
┌──────────┬──────────┬────────────┐
│ column_1 ┆ column_2 ┆ column_3 │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ date │
╞══════════╪══════════╪════════════╡
│ Ada ┆ 410 ┆ 2024-03-01 │
│ Bo ┆ 380 ┆ 2024-03-09 │
└──────────┴──────────┴────────────┘
shape: (1, 3)
┌──────┬─────┬────────────┐
│ bear ┆ kg ┆ seen │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ date │
╞══════╪═════╪════════════╡
│ Bo ┆ 380 ┆ 2024-03-09 │
└──────┴─────┴────────────┘
1
- WHEN
readExcel(path, sheetName = "nope")is called - THEN
IOErroris raised
- WHEN a frame of strings, integers, floats, booleans and dates is written and read back
- THEN the result equals the frame
Reading OpenDocument
readOds SHALL read a sheet of an .ods file with the options of readExcel.
echo readOds("tests/data/bears.ods")
shape: (2, 2)
┌──────┬─────┐
│ bear ┆ kg │
│ --- ┆ --- │
│ str ┆ i64 │
╞══════╪═════╡
│ Ada ┆ 410 │
│ Bo ┆ 380 │
└──────┴─────┘
- WHEN an .ods sheet with numeric cells is read
- THEN those columns are Float64
expression-plugins
Purpose: Calling Polars expression plugins (shared libraries implementing the Polars plugin ABI) from Nanuq, as register_plugin_function does in Python Polars.
Calling an expression plugin
registerPluginFunction(pluginPath, functionName, args) SHALL give an expression that calls the function functionName of the Polars expression plugin at pluginPath (a shared library implementing the Polars plugin ABI 0.1) on the columns of args, with the options of Python's register_plugin_function (kwargs as pickled bytes, isElementwise, changesLength, returnsScalar, castToSupertype, inputWildcardExpansion, passNameToApply, isDeterministic). The output name and data type SHALL be the ones the plugin reports, extension types included. The expression SHALL compose like any other, lazily and in group-bys.
# tests/data/plugins/double_it.nim, built as a library
let lib = "tests/data/plugins/" & (DynlibFormat % "double_it")
let df = newDataFrame(series("x", [1.5, 2.0, 4.0]))
echo df.select(registerPluginFunction(lib, "double_it", [col"x"], isElementwise = true))
shape: (3, 1)
┌─────┐
│ x │
│ --- │
│ f64 │
╞═════╡
│ 3.0 │
│ 4.0 │
│ 8.0 │
└─────┘
- WHEN the plugin reports an error for a call (it returns no column and sets its last error message)
- THEN running the query raises
ComputeErrorwith the plugin's message
- WHEN
pluginPathis not a loadable library - THEN running the query raises
ComputeErrornaming the path
- WHEN the plugin's output field carries
ARROW:extension:name - THEN the column has that extension type, shown as
ext[<name>]
expressions
Purpose: Expressions beyond the basics: conditionals, membership and range tests, extra arithmetic, rounding and aggregations, null fill strategies, and window expressions.
Conditional expressions
The API SHALL build conditional expressions with the chain when(cond).then(value) , optionally followed by more .when(cond).then(value) pairs and .otherwise(value). Rows matching no condition SHALL be null when there is no otherwise. A chain SHALL be usable wherever an Expr is expected. Values SHALL be expressions or Nim literals, and strings SHALL be literal values.
let bears = newDataFrame(series("w", [100, 300, 900]))
echo bears.select(
`when`(col("w") < 150).then("cub")
.when(col("w") < 500).then("adult")
.otherwise("chonk")
.alias("size"))
shape: (3, 1)
┌───────┐
│ size │
│ --- │
│ str │
╞═══════╡
│ cub │
│ adult │
│ chonk │
└───────┘
- WHEN
when(col("w") < 150).then("cub").when(col("w") < 500).then("adult").otherwise("chonk")is selected over weights 100, 300 and 900 - THEN the result is "cub", "adult" and "chonk"
- WHEN
when(col("w") < 150).then(1)is selected over weights 100 and 900 - THEN the result is 1 and null
choose macro
The API SHALL provide a choose macro that turns an if/elif/else expression with expression conditions into the same chain. A missing else SHALL mean null. Any other body SHALL fail to compile.
let bears = newDataFrame(series("w", [100, 300, 900]))
let size = choose:
if col("w") < 150: "cub"
elif col("w") < 500: "adult"
else: "chonk"
echo bears.select(col("w"), size.alias("size"))
shape: (3, 2)
┌─────┬───────┐
│ w ┆ size │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪═══════╡
│ 100 ┆ cub │
│ 300 ┆ adult │
│ 900 ┆ chonk │
└─────┴───────┘
- WHEN a
chooseblock and the equivalent chain are built - THEN their
$strings are equal
- WHEN
choose(if col("collared"): "tracked" else: "free")is selected - THEN each row is "tracked" or "free"
Membership and ranges
Expr SHALL support isIn(values) for a list of Nim values or an expression, with nullsEqual = false, and isBetween(lower, upper, closed = Both) with a pure enum ClosedInterval (Both, Left, Right, None).
let df = newDataFrame(series("a", [1, 2, 3]))
echo df.select(
col("a"),
col("a").isIn([1, 3]).alias("in_1_3"),
col("a").isBetween(1, 3, closed = Left).alias("in_[1,3)"))
shape: (3, 3)
┌─────┬────────┬──────────┐
│ a ┆ in_1_3 ┆ in_[1,3) │
│ --- ┆ --- ┆ --- │
│ i64 ┆ bool ┆ bool │
╞═════╪════════╪══════════╡
│ 1 ┆ true ┆ true │
│ 2 ┆ false ┆ true │
│ 3 ┆ true ┆ false │
└─────┴────────┴──────────┘
- WHEN
col("a").isIn([1, 3])is selected over 1, 2 and 3 - THEN the result is true, false and true
- WHEN
col("a").isBetween(1, 3, closed = Left)is selected over 1, 2 and 3 - THEN the result is true, true and false
Arithmetic operators
Expr SHALL support mod, div (floor division), ^ and pow, abs and unary -, with Nim literals on either side of a binary operator. mod and div SHALL follow Polars' floor semantics.
let df = newDataFrame(series("a", [-7, 3]))
echo df.select(col("a"), (col("a") mod 3).alias("mod"), (col("a") div 3).alias("div"),
(col("a") ^ 2).alias("sq"), abs(col("a")).alias("abs"))
shape: (2, 5)
┌─────┬─────┬─────┬─────┬─────┐
│ a ┆ mod ┆ div ┆ sq ┆ abs │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╪═════╪═════╡
│ -7 ┆ 2 ┆ -3 ┆ 49 ┆ 7 │
│ 3 ┆ 0 ┆ 1 ┆ 9 ┆ 3 │
└─────┴─────┴─────┴─────┴─────┘
- WHEN
lit(-7) mod 3andlit(-7) div 3are evaluated - THEN the results are 2 and -3
- WHEN
col("a") ^ 2is selected over 3 - THEN the result is 9
Rounding
Expr SHALL support round(decimals = 0, mode = HalfToEven) with a pure enum RoundMode (HalfToEven, HalfAwayFromZero, ToZero).
let df = newDataFrame(series("w", [1.23456, 2.5]))
echo df.select(col("w").round(2).alias("r2"), col("w").round.alias("even"),
col("w").round(mode = HalfAwayFromZero).alias("away"))
shape: (2, 3)
┌──────┬──────┬──────┐
│ r2 ┆ even ┆ away │
│ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ f64 │
╞══════╪══════╪══════╡
│ 1.23 ┆ 1.0 ┆ 1.0 │
│ 2.5 ┆ 2.0 ┆ 3.0 │
└──────┴──────┴──────┘
- WHEN
col("w").round(2)is selected over 1.23456 - THEN the result is 1.23
- WHEN
col("w").roundandcol("w").round(mode = HalfAwayFromZero)are selected over 2.5 - THEN the results are 2.0 and 3.0
More aggregations
Expr SHALL support median, var(ddof = 1), std(ddof = 1), quantile(q, interpolation = Nearest) with a pure enum QuantileMethod (Nearest, Lower, Higher, Midpoint, Linear, Equiprobable), and len, which counts rows including nulls.
let df = newDataFrame(series("a", [some(1), some(2), none(int), some(4)]))
echo df.select(col("a").median.alias("median"),
col("a").quantile(0.5, interpolation = Linear).alias("q50"),
col("a").len.alias("len"), col("a").count.alias("count"))
shape: (1, 4)
┌────────┬─────┬─────┬───────┐
│ median ┆ q50 ┆ len ┆ count │
│ --- ┆ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ u32 ┆ u32 │
╞════════╪═════╪═════╪═══════╡
│ 2.0 ┆ 2.0 ┆ 4 ┆ 3 │
└────────┴─────┴─────┴───────┘
- WHEN
medianandquantile(0.25, interpolation = Linear)are computed over 1, 2, 3 and 4 - THEN the results are 2.5 and 1.75
- WHEN
lenandcountare computed over 1, null and 3 - THEN the results are 3 and 2
Null fill strategies
Expr SHALL support fillNull(strategy, limit = none(int)) with a pure enum FillNullStrategy (Forward, Backward, Mean, Min, Max, Zero, One), and the shortcuts forwardFill(limit) and backwardFill(limit). limit SHALL also accept a plain int. A limit SHALL bound how many consecutive nulls are filled.
let df = newDataFrame(series("a", [some(1), none(int), none(int), some(4)]))
echo df.select(col("a"), col("a").forwardFill(1).alias("ffill1"),
col("a").backwardFill.alias("bfill"), col("a").fillNull(Mean).alias("mean"))
shape: (4, 4)
┌──────┬────────┬───────┬──────┐
│ a ┆ ffill1 ┆ bfill ┆ mean │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 │
╞══════╪════════╪═══════╪══════╡
│ 1 ┆ 1 ┆ 1 ┆ 1 │
│ null ┆ 1 ┆ 4 ┆ 2 │
│ null ┆ null ┆ 4 ┆ 2 │
│ 4 ┆ 4 ┆ 4 ┆ 4 │
└──────┴────────┴───────┴──────┘
- WHEN
col("a").forwardFill(1)is selected over 1, null, null and 4 - THEN the result is 1, 1, null and 4
- WHEN
col("a").fillNull(Mean)is selected over 1, null and 3 - THEN the result is 1, 2 and 3
Window expressions
Expr SHALL support over(partitionBy) with one column name, a list of names, or a list of expressions. It SHALL compute the expression per group and return one value per row.
let df = newDataFrame(series("g", ["x", "x", "y"]), series("v", [1, 3, 10]))
echo df.withColumns(col("v").mean.over("g").alias("group_mean"))
shape: (3, 3)
┌─────┬─────┬────────────┐
│ g ┆ v ┆ group_mean │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ f64 │
╞═════╪═════╪════════════╡
│ x ┆ 1 ┆ 2.0 │
│ x ┆ 3 ┆ 2.0 │
│ y ┆ 10 ┆ 10.0 │
└─────┴─────┴────────────┘
- WHEN
col("v").mean.over("g")is selected over groups x, x, y with values 1, 3, 10 - THEN the result is 2, 2 and 10
- WHEN
col("r").forwardFill.over("g")runs where group y starts with a null - THEN that null stays null, instead of taking the last value of group x
Ranking
Expr SHALL support rank(how = Average, descending = false, seed = none(int)) with a pure enum RankMethod (Average, Min, Max, Dense, Ordinal, Random), giving each value its rank from 1. Ties SHALL be handled as Polars does: Average gives tied values the mean of their ranks (f64), Min and Max the lowest or highest (u32), Dense leaves no gaps after ties, and Ordinal breaks ties by position. seed SHALL make Random repeatable. Nulls SHALL stay null.
let roll = newDataFrame:
rider: ["Merckx", "Pogačar", "De Vlaeminck", "Van Looy", "Kelly"]
monuments: [19, 13, 11, 8, 9]
echo roll.select(col.rider, col.monuments,
col.monuments.rank(Min, descending = true).alias("place"),
col.monuments.rank.alias("avg"))
shape: (5, 4)
┌──────────────┬───────────┬───────┬─────┐
│ rider ┆ monuments ┆ place ┆ avg │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ u32 ┆ f64 │
╞══════════════╪═══════════╪═══════╪═════╡
│ Merckx ┆ 19 ┆ 1 ┆ 5.0 │
│ Pogačar ┆ 13 ┆ 2 ┆ 4.0 │
│ De Vlaeminck ┆ 11 ┆ 3 ┆ 3.0 │
│ Van Looy ┆ 8 ┆ 5 ┆ 1.0 │
│ Kelly ┆ 9 ┆ 4 ┆ 2.0 │
└──────────────┴───────────┴───────┴─────┘
- WHEN
rank(Min, descending = true)runs over 9, 9, 7 - THEN the result is 1, 1, 3
- WHEN
rank(Dense)runs over 9, 9, 7 - THEN the result is 2, 2, 1
- WHEN
rank()runs over 9, 9, 7 - THEN the result is 2.5, 2.5, 1.0 with dtype f64
Filtering inside expressions
e.filter(predicate) SHALL keep the values of e where predicate is true, so that an aggregation can run over part of each group.
let df = newDataFrame:
rider: ["Pogačar", "Pogačar", "Vingegaard", "Vingegaard"]
stage: ["TT", "road", "TT", "road"]
secs: [3120, 15400, 3150, 15390]
echo df.groupBy(col.rider).agg(col.secs.filter(col.stage == "TT").sum.alias("tt_secs"))
.sort("rider")
shape: (2, 2)
┌────────────┬─────────┐
│ rider ┆ tt_secs │
│ --- ┆ --- │
│ str ┆ i64 │
╞════════════╪═════════╡
│ Pogačar ┆ 3120 │
│ Vingegaard ┆ 3150 │
└────────────┴─────────┘
- WHEN
col.secs.filter(col.stage == "TT").sumis aggregated per rider - THEN each rider's sum counts only the TT rows
Shape and position aggregations
Expressions SHALL have the aggregations product, mode (every most frequent value, in order of appearance), argMin and argMax (the row index of the first minimum or maximum), skew(bias = true) and kurtosis(fisher = true, bias = true).
let df = newDataFrame:
year: [2020, 2021, 2022, 2023]
oni: [0.5, -1.0, -0.9, 1.9]
echo df.select(col.oni.argMax.alias("warmest_row"),
col.oni.argMin.alias("coldest_row"), col.oni.skew.round(3).alias("skew"))
shape: (1, 3)
┌─────────────┬─────────────┬───────┐
│ warmest_row ┆ coldest_row ┆ skew │
│ --- ┆ --- ┆ --- │
│ u32 ┆ u32 ┆ f64 │
╞═════════════╪═════════════╪═══════╡
│ 3 ┆ 1 ┆ 0.474 │
└─────────────┴─────────────┴───────┘
- WHEN
productruns on 2, 3, 4 - THEN the result is 24
- WHEN
moderuns on 1, 2, 2, 3, 3 - THEN the result holds 2 and 3
Boolean aggregations
Expr SHALL support any(ignoreNulls = true) and all(ignoreNulls = true) on boolean columns, as aggregations: whether any value, or every value, is true. With ignoreNulls = false they SHALL follow Kleene logic: any is null when there are nulls and no true value, all is null when there are nulls and no false value. The all() selector (no arguments) SHALL keep working.
let df = newDataFrame:
team: ["a", "a", "b", "b"]
won: [true, false, true, true]
echo df.groupBy("team").agg(col.won.all.alias("always"), col.won.any.alias("ever"))
shape: (2, 3)
┌──────┬────────┬──────┐
│ team ┆ always ┆ ever │
│ --- ┆ --- ┆ --- │
│ str ┆ bool ┆ bool │
╞══════╪════════╪══════╡
│ a ┆ false ┆ true │
│ b ┆ true ┆ true │
└──────┴────────┴──────┘
- WHEN
any(ignoreNulls = false)runs on false and null - THEN the result is null
Entropy
Expr SHALL support entropy(base = E, normalize = true), an aggregation giving -sum(p * ln(p)) / ln(base), where p are the values (divided by their sum when normalize is true).
let df = newDataFrame:
votes: [@[1, 1, 2], @[5]]
echo df.select(col.votes.list.agg(element().entropy).alias("entropy"))
shape: (2, 1)
┌──────────┐
│ entropy │
│ --- │
│ f64 │
╞══════════╡
│ 1.039721 │
│ 0.0 │
└──────────┘
- WHEN the entropy of a single positive value is computed
- THEN the result is 0.0
Row count expression
len() with no argument SHALL be an expression counting rows, named len (Python's pl.len()); in a group-by it SHALL count the rows of each group.
let df = newDataFrame:
team: ["a", "a", "b"]
echo df.groupBy("team").agg(len())
shape: (2, 2)
┌──────┬─────┐
│ team ┆ len │
│ --- ┆ --- │
│ str ┆ u32 │
╞══════╪═════╡
│ a ┆ 2 │
│ b ┆ 1 │
└──────┴─────┘
- WHEN
df.select(len())runs on 4 rows - THEN the result is one row with
len= 4
Several window keys and selector concatenation
over SHALL take several column names as separate arguments, and concatStr SHALL take selectors, expanding them to their columns.
let df = newDataFrame(series("c", @["x", "x", "y"]), series("b", @["p", "p", "q"]))
echo df.select(concatStr([all()], "-").alias("s"), lit(1).sum.over("c", "b").alias("n"))
shape: (3, 2)
┌─────┬─────┐
│ s ┆ n │
│ --- ┆ --- │
│ str ┆ i32 │
╞═════╪═════╡
│ x-p ┆ 1 │
│ x-p ┆ 1 │
│ y-q ┆ 1 │
└─────┴─────┘
- WHEN
col("v").sum.over("c", "b")is selected - THEN each row gets the sum of its (c, b) group
Null-aware comparisons and closeness
eqMissing(other) and neMissing(other) SHALL compare as == and != with null equal to null, never giving null. isClose(other, absTol = 0.0, relTol = 1e-9, nansEqual = false) SHALL be true where abs(a - b) <= max(relTol * max(abs(a), abs(b)), absTol).
let df = newDataFrame(series("a", [some(1.0), none(float)]), series("b", [some(1.05), none(float)]))
echo df.select(col("a").eqMissing(col("b")).alias("eq"),
col("a").isClose(col("b"), absTol = 0.1).alias("close"))
shape: (2, 2)
┌───────┬───────┐
│ eq ┆ close │
│ --- ┆ --- │
│ bool ┆ bool │
╞═══════╪═══════╡
│ false ┆ true │
│ true ┆ null │
└───────┴───────┘
- WHEN
eqMissingcompares null with null - THEN the result is true
More expression functions
nth(indices) SHALL select columns by position (negative from the end). cumulativeEval(expr, minSamples = 1) SHALL run expr on the growing window up to each row, roundSigFigs(digits) SHALL round to significant figures, reinterpret(signed) SHALL read 64-bit integer bits as Int64 or UInt64, and concatArr(exprs) SHALL build fixed-size arrays per row.
let df = newDataFrame(series("x", @[1.0, 22.0, 333.0]), series("y", @[4.0, 5.0, 6.0]))
echo df.select(nth(-1), col("x").cumulativeEval(element().sum).alias("cum"),
col("x").roundSigFigs(1).alias("sig"), concatArr(col("x"), col("y")).alias("xy"))
shape: (3, 4)
┌─────┬───────┬───────┬───────────────┐
│ y ┆ cum ┆ sig ┆ xy │
│ --- ┆ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ f64 ┆ array[f64, 2] │
╞═════╪═══════╪═══════╪═══════════════╡
│ 4.0 ┆ 1.0 ┆ 1.0 ┆ [1.0, 4.0] │
│ 5.0 ┆ 23.0 ┆ 20.0 ┆ [22.0, 5.0] │
│ 6.0 ┆ 356.0 ┆ 300.0 ┆ [333.0, 6.0] │
└─────┴───────┴───────┴───────────────┘
- WHEN
cumulativeEval(element().sum)runs on 1, 2, 3 - THEN the result is 1, 3, 6
frame-utilities
Purpose: Smaller expression and frame functions: sampling, hashing, meta, comparing, stacking, updating and upsampling.
Smaller expression functions
Expressions SHALL have shuffle(seed), sample(n or fraction), hash(seed), get(i), argTrue, upperBound, lowerBound, extendConstant(value, n), rle (a struct of len and value) and reshape(dims), and over(partitionBy, mappingStrategy) with MappingStrategy.GroupToRows, Join or Explode.
let df = newDataFrame:
den: ["A", "A", "B"]
kg: [410, 380, 500]
echo df.select(col("kg").get(1).alias("second"), col("kg").upperBound.alias("max"))
echo df.select((col("kg") > 400).argTrue.alias("heavy"))
echo df.select(col("den"), col("kg").over("den", MappingStrategy.Join).alias("all"))
echo df.select(col("den").rle).unnest("den")
shape: (1, 2)
┌────────┬─────────────────────┐
│ second ┆ max │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞════════╪═════════════════════╡
│ 380 ┆ 9223372036854775807 │
└────────┴─────────────────────┘
shape: (2, 1)
┌───────┐
│ heavy │
│ --- │
│ u32 │
╞═══════╡
│ 0 │
│ 2 │
└───────┘
shape: (3, 2)
┌─────┬────────────┐
│ den ┆ all │
│ --- ┆ --- │
│ str ┆ list[i64] │
╞═════╪════════════╡
│ A ┆ [410, 380] │
│ A ┆ [410, 380] │
│ B ┆ [500] │
└─────┴────────────┘
shape: (2, 2)
┌─────┬───────┐
│ len ┆ value │
│ --- ┆ --- │
│ u32 ┆ str │
╞═════╪═══════╡
│ 2 ┆ A │
│ 1 ┆ B │
└─────┴───────┘
- WHEN
shuffle(seed = 1)is evaluated twice - THEN both results are the same permutation
Names and meta
name.toLowercase and name.toUppercase SHALL change output names, and e.meta SHALL give outputName, rootNames, hasMultipleOutputs, isColumn, isLiteral and undoAliases.
let e = (col("kg") * 2).alias("double")
echo e.meta.outputName, " ", e.meta.rootNames, " ", col("*").meta.hasMultipleOutputs
let df = newDataFrame:
Bear: ["Ada"]
echo df.select(col("Bear").name.toUppercase).columns
double @["kg"] true
@["BEAR"]
- WHEN
outputNameis asked ofcol("*") - THEN
ComputeErroris raised
Comparing and stacking frames
a.equals(b, nullEqual = true) SHALL tell whether two frames (or Series) have the same names, types and values; vstack and extend SHALL append the rows of a frame with the same schema, and hstack SHALL add Series or the columns of another frame.
let a = newDataFrame:
bear: ["Ada"]
kg: [410]
let b = newDataFrame:
bear: ["Bo"]
kg: [380]
echo a.vstack(b).hstack([series("den", ["A", "B"])])
echo a.equals(a), " ", a.equals(b)
shape: (2, 3)
┌──────┬─────┬─────┐
│ bear ┆ kg ┆ den │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ str │
╞══════╪═════╪═════╡
│ Ada ┆ 410 ┆ A │
│ Bo ┆ 380 ┆ B │
└──────┴─────┴─────┘
true false
- WHEN two frames with a null in the same place are compared with
nullEqual = false - THEN
equalsis false
Updating, upsampling and partitions
df.update(other, on, how) SHALL replace values of df with the non-null values of other in matching rows; df.upsample(timeColumn, every, groupBy) SHALL insert rows for missing times at a regular interval; estimatedSize SHALL give the frame's size; partitionBy(by, asDict = true) SHALL give a table from key values to frames; and collectAll(lfs) SHALL collect several LazyFrames.
let df = newDataFrame:
bear: ["Ada", "Bo"]
kg: [410, 380]
let fix = newDataFrame:
bear: ["Bo"]
kg: [395]
echo df.update(fix, on = "bear")
let t = newDataFrame:
day: [date(2026, 3, 1), date(2026, 3, 4)]
seen: [3, 1]
echo t.upsample("day", every = "1d")
echo df.partitionBy("bear", asDict = true).len, " ", collectAll([df.lazy, fix.lazy]).len
shape: (2, 2)
┌──────┬─────┐
│ bear ┆ kg │
│ --- ┆ --- │
│ str ┆ i64 │
╞══════╪═════╡
│ Ada ┆ 410 │
│ Bo ┆ 395 │
└──────┴─────┘
shape: (4, 2)
┌────────────┬──────┐
│ day ┆ seen │
│ --- ┆ --- │
│ date ┆ i64 │
╞════════════╪══════╡
│ 2026-03-01 ┆ 3 │
│ 2026-03-02 ┆ null │
│ 2026-03-03 ┆ null │
│ 2026-03-04 ┆ 1 │
└────────────┴──────┘
2 2
- WHEN
upsampleis called withgroupBy - THEN each group is filled between its own first and last time
Operator methods and xor
Expressions SHALL have the method spellings add, sub, mul, truediv, floordiv, eq, ne, lt, le, gt, ge (with an expression, number, string or bool) and neg, giving the same result as the operators, and xor SHALL be logical on booleans and bitwise on integers.
let df = newDataFrame(series("a", @[6, 3]), series("ok", @[true, false]))
echo df.select(col("a").mul(2).alias("m"), col("a").floordiv(4).alias("f"),
(col("a") xor 5).alias("x"), (col("ok") xor true).alias("nx"))
shape: (2, 4)
┌─────┬─────┬─────┬───────┐
│ m ┆ f ┆ x ┆ nx │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ bool │
╞═════╪═════╪═════╪═══════╡
│ 12 ┆ 1 ┆ 3 ┆ false │
│ 6 ┆ 0 ┆ 6 ┆ true │
└─────┴─────┴─────┴───────┘
- WHEN
col("a").sub(1)andcol("a") - 1are selected - THEN both columns are equal
Ranges per row
intRanges(start, stop, step = 1, dtype = Int64), dateRanges(start, stop, interval) and datetimeRanges(start, stop, interval, closed, timeUnit, timeZone) SHALL give one list per row, with columns or values as bounds; arange SHALL be intRange.
let df = newDataFrame(series("lo", @[1, 3]), series("hi", @[3, 6]))
echo df.select(intRanges(col("lo"), col("hi")).alias("r"))
shape: (2, 1)
┌───────────┐
│ r │
│ --- │
│ list[i64] │
╞═══════════╡
│ [1, 2] │
│ [3, 4, 5] │
└───────────┘
- WHEN
dateRangesruns from 2024-01-01 to 2024-01-03 - THEN the list holds 3 dates
Inequality joins
joinWhere(other, predicates..., suffix = "_right") on DataFrames and LazyFrames SHALL join the rows of both frames for which every predicate holds; clashing columns of other SHALL get suffix.
let east = newDataFrame(series("id", @[100, 101]), series("dur", @[140, 100]))
let west = newDataFrame(series("t_id", @[404, 498]), series("time", @[90, 130]))
echo east.joinWhere(west, col("dur") < col("time"))
shape: (1, 4)
┌─────┬─────┬──────┬──────┐
│ id ┆ dur ┆ t_id ┆ time │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪══════╪══════╡
│ 101 ┆ 100 ┆ 498 ┆ 130 │
└─────┴─────┴──────┴──────┘
- WHEN no pair of rows satisfies the predicates
- THEN the result has no rows
Frame and Series helpers
The API SHALL provide append (rows of another frame, in place), remove(predicate) (rows where it is not true), setSorted, Series.isSorted(descending, nullsLast), explainAll(lfs), threadPoolSize(), readParquetSchema(path), fromEpoch(column, unit), hist(bins, binCount, includeCategory, includeBreakpoint) on Expr and Series, Series.scatter(indices, values) and set(mask, value) .
var df = newDataFrame(series("a", @[1, 2]))
df.append(newDataFrame(series("a", @[3])))
echo df.remove(col("a") == 2)
echo series("x", @[1.0, 2.0, 2.5, 4.0]).hist(bins = [0.0, 2.0, 4.0])
echo series("x", @[1, 2, 3]).scatter([0, 2], [10, 30])
shape: (2, 1)
┌─────┐
│ a │
│ --- │
│ i64 │
╞═════╡
│ 1 │
│ 3 │
└─────┘
shape: (2, 3)
┌────────────┬────────────┬───────┐
│ breakpoint ┆ category ┆ count │
│ --- ┆ --- ┆ --- │
│ f64 ┆ cat ┆ u32 │
╞════════════╪════════════╪═══════╡
│ 2.0 ┆ [0.0, 2.0] ┆ 2 │
│ 4.0 ┆ (2.0, 4.0] ┆ 2 │
└────────────┴────────────┴───────┘
shape: (3,)
Series: 'x' [i64]
[
10
2
30
]
- WHEN
remove(col("a") > 1)runs on a column with a null - THEN the null row stays
Unstack
unstack(step, how = UnstackDirection.Vertical, columns = [], fillValues = nil) SHALL reshape each column into columns <name>_<i> of step values each (Vertical) or with step values per row (Horizontal), padding the end with nulls or fillValues.
let df = newDataFrame(series("x", @["a", "b", "c", "d", "e"]))
echo df.unstack(2)
shape: (2, 3)
┌─────┬─────┬──────┐
│ x_0 ┆ x_1 ┆ x_2 │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞═════╪═════╪══════╡
│ a ┆ c ┆ e │
│ b ┆ d ┆ null │
└─────┴─────┴──────┘
- WHEN 5 values are unstacked horizontally with step 2 and fill 0
- THEN column
_0holds values 1, 3, 5 and column_1holds 2, 4, 0
Rolling Nim functions
rollingMap(f, windowSize, minPeriods = windowSize, center = false) SHALL apply a typed Nim proc to each window's non-null values, giving null when a window has fewer than minPeriods values.
import std/sequtils
let df = newDataFrame(series("x", @[1.0, 2.0, 3.0, 4.0]))
echo df.select(col("x").rollingMap(proc (w: seq[float]): float = w.foldl(a + b), windowSize = 2))
shape: (4, 1)
┌──────┐
│ x │
│ --- │
│ f64 │
╞══════╡
│ null │
│ 3.0 │
│ 5.0 │
│ 7.0 │
└──────┘
- WHEN
center = truewith window 3 - THEN each value's window is the value and its two neighbours
Data type of an expression
dtypeOf(expr or column) SHALL stand for the type of an expression at run time: cast(e, dtypeOf(...)) casts to it, display gives its short name as a string value, innerDtype the inner type of a List or Array.
let df = newDataFrame(series("a", @[1.5, 2.5]), series("b", @[1'i32, 2'i32]))
echo df.select(col("a").cast(dtypeOf("b"), strict = false), dtypeOf("b").display.alias("type"))
shape: (2, 2)
┌─────┬──────┐
│ a ┆ type │
│ --- ┆ --- │
│ i32 ┆ str │
╞═════╪══════╡
│ 1 ┆ i32 │
│ 2 ┆ i32 │
└─────┴──────┘
- WHEN
dtypeOf("nope")is used - THEN
ColumnNotFoundErroris raised when the query runs
Empty frames
newDataFrame(schema = {...}) SHALL build a frame with those columns and types and no rows (a Schema works too). clear(n = 0) on a DataFrame or LazyFrame SHALL keep the columns and types with no rows, or n rows of nulls. isEmpty on a DataFrame or Series SHALL be true when it has no rows.
let empty = newDataFrame(schema = {"bear": String, "kg": Int64})
echo empty
echo empty.isEmpty
echo newDataFrame(series("kg", @[410, 380])).clear(1)
shape: (0, 2)
┌──────┬─────┐
│ bear ┆ kg │
│ --- ┆ --- │
│ str ┆ i64 │
╞══════╪═════╡
└──────┴─────┘
true
shape: (1, 1)
┌──────┐
│ kg │
│ --- │
│ i64 │
╞══════╡
│ null │
└──────┘
- WHEN
df.clearruns - THEN its schema equals
df.schemaand its height is 0
Frame shortcuts
getColumnIndex(name) SHALL give a column's position (raising ColumnNotFoundError). rowsByKey(key, K, T, unique = false) SHALL group the rows, as T objects or tuples, by the values of key in order of appearance (with unique, the last row per key). shift(n, fillValue) and dropNans(subset) SHALL work on frames as on each column; LazyFrame first and last SHALL keep the first or last row. rechunk SHALL put each column in one chunk, shrinkToFit SHALL drop spare capacity, and nChunks SHALL count chunks.
import std/tables
let df = newDataFrame(series("station", @["A", "B", "A"]), series("rain", @[1.5, NaN, 3.0]))
echo df.getColumnIndex("rain")
echo df.rowsByKey("station", string, tuple[rain: float])
echo df.dropNans.shift(1)
1
{"A": @[(rain: 1.5), (rain: 3.0)], "B": @[(rain: nan)]}
shape: (2, 2)
┌─────────┬──────┐
│ station ┆ rain │
│ --- ┆ --- │
│ str ┆ f64 │
╞═════════╪══════╡
│ null ┆ null │
│ A ┆ 1.5 │
└─────────┴──────┘
- WHEN
getColumnIndex("nope")runs - THEN
ColumnNotFoundErroris raised
Schema matching
matchToSchema(schema, missingColumns, extraColumns, integerCast, floatCast) SHALL put the columns in the schema's order and types. A missing column SHALL raise unless missingColumns = Insert (nulls), an extra column SHALL raise unless extraColumns = Ignore, and integers and floats SHALL change type only with CastPolicy.Upcast.
let df = newDataFrame(series("b", @[1'i32]), series("a", @["x"]))
echo df.matchToSchema({"a": String, "b": Int64, "c": Float64},
missingColumns = MissingColumns.Insert, integerCast = CastPolicy.Upcast)
shape: (1, 3)
┌─────┬─────┬──────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ f64 │
╞═════╪═════╪══════╡
│ x ┆ 1 ┆ null │
└─────┴─────┴──────┘
- WHEN the schema has a column the frame lacks and
missingColumnsisRaise - THEN
PolarsErroris raised
Merging sorted frames
mergeSorted(other, key) SHALL merge two frames sorted by key into one sorted frame.
let a = newDataFrame(series("k", @[1, 4]))
let b = newDataFrame(series("k", @[2, 3, 5]))
echo a.mergeSorted(b, "k").toList("k", int)
@[1, 2, 3, 4, 5]
- WHEN both frames have the same columns, sorted by
key - THEN the result has all their rows, sorted
Query optimizations
cache SHALL mark part of a query to compute once. QueryOptFlags SHALL hold the optimization switches (all on by default; QueryOptFlags.none turns off all but type coercion and checks), applied with withOptimizations or collect(optimizations, engine).
let lf = newDataFrame(series("x", @[1, 2, 3])).lazy.filter(col("x") > 1)
echo lf.collect(QueryOptFlags.none).height
echo lf.cache.collect(QueryOptFlags(predicatePushdown: false)).height
2
2
- WHEN a query is collected with every optimization on and with
QueryOptFlags.none - THEN the rows are the same
frame-verbs
Purpose: Column and row verbs on DataFrames and LazyFrames: dropping and renaming columns, row windows, unique rows, row indexes, sorting by several keys, and sampling.
Dropping and renaming columns
LazyFrame and DataFrame SHALL support drop(columns, strict = true), with one column name or a list of names, and rename(mapping: openArray[(string, string)], strict = true). With strict = true, a column that does not exist SHALL raise PolarsError. With strict = false, it SHALL be ignored.
let df = newDataFrame(series("a", [1]), series("b", [2]), series("c", [3]))
echo df.drop("b").columns # one name
echo df.drop(["a", "b"]).columns # several
echo df.drop("zzz", strict = false).columns
echo df.rename({"a": "x"}).columns
@["a", "c"]
@["c"]
@["a", "b", "c"]
@["x", "b", "c"]
- WHEN
df.drop("b")runs on columnsa,b,c - THEN the columns are
a,c, anddf.drop(["a", "b"])leavesc
- WHEN
df.rename({"a": "x"})runs on columnsa,b - THEN the columns are
x,b
- WHEN
df.drop("zzz")runs - THEN
PolarsErroris raised, anddf.drop("zzz", strict = false)returns the frame unchanged
Row windows
LazyFrame and DataFrame SHALL support head(n = 5), tail(n = 5), slice(offset) and slice(offset, length). A negative offset SHALL count from the end. reverse() SHALL reverse the row order.
let df = newDataFrame(series("n", [1, 2, 3, 4, 5]))
echo df.tail(2).toList("n", int)
echo df.slice(-3, 2).toList("n", int) # negative offset counts from the end
echo df.slice(1).toList("n", int) # to the end
echo df.reverse.toList("n", int)
@[4, 5]
@[3, 4]
@[2, 3, 4, 5]
@[5, 4, 3, 2, 1]
- WHEN
tail(2)runs on rows 1 to 5 - THEN the result is rows 4 and 5
- WHEN
slice(-3, 2)runs on rows 1 to 5 - THEN the result is rows 3 and 4
- WHEN
slice(1)runs on rows 1 to 5 - THEN the result is rows 2 to 5
Unique rows
LazyFrame and DataFrame SHALL support unique(subset = [], keep, maintainOrder = false), with one column name or a list of names, judging duplicates on all columns when the subset is empty. keep is a pure enum UniqueKeepStrategy (Any (default), First, Last, None). With maintainOrder = true, the rows SHALL keep their original order.
let df = newDataFrame(series("k", ["a", "b", "a"]), series("v", [1, 2, 3]))
echo df.unique("k", keep = First, maintainOrder = true)
echo df.unique("k", keep = None)
shape: (2, 2)
┌─────┬─────┐
│ k ┆ v │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ a ┆ 1 │
│ b ┆ 2 │
└─────┴─────┘
shape: (1, 2)
┌─────┬─────┐
│ k ┆ v │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ b ┆ 2 │
└─────┴─────┘
- WHEN
unique("k", keep = First, maintainOrder = true)runs on keys a, b, a with values 1, 2, 3 - THEN the result is (a, 1), (b, 2)
- WHEN the same frame is made unique on
kwithkeep = None - THEN only (b, 2) remains
Row index
LazyFrame and DataFrame SHALL support withRowIndex(name = "index", offset = 0), which adds an unsigned integer column with that name as the first column, counting from offset.
let df = newDataFrame(series("bear", ["Nanuq", "Ursa", "Kuma"]))
echo df.withRowIndex("n", offset = 1)
shape: (3, 2)
┌─────┬───────┐
│ n ┆ bear │
│ --- ┆ --- │
│ u32 ┆ str │
╞═════╪═══════╡
│ 1 ┆ Nanuq │
│ 2 ┆ Ursa │
│ 3 ┆ Kuma │
└─────┴───────┘
- WHEN
withRowIndex("n", offset = 1)runs on three rows - THEN the first column is
nwith values 1, 2, 3
Sorting by several keys
LazyFrame and DataFrame SHALL sort by several column names or expressions with sort(by, descending: openArray[bool] = [], nullsLast: openArray[bool] = [], maintainOrder = false). An empty list SHALL mean false for every key, and one value SHALL apply to every key. Another length SHALL raise PolarsError. The one-column sort(by: string, descending = false, nullsLast = false, maintainOrder = false) SHALL remain.
let df = newDataFrame(series("g", ["b", "a", "b", "a"]), series("v", [1, 2, 3, 4]))
echo df.sort(["g", "v"], descending = [false, true])
shape: (4, 2)
┌─────┬─────┐
│ g ┆ v │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ a ┆ 4 │
│ a ┆ 2 │
│ b ┆ 3 │
│ b ┆ 1 │
└─────┴─────┘
- WHEN a frame is sorted by
["g", "v"]withdescending = [false, true] - THEN rows are ordered by
gascending and, within eachg, byvdescending
- WHEN a column holding null, 2, 1 is sorted with
nullsLast = true - THEN the order is 1, 2, null
- WHEN a sort by three keys gets
descending = [true, false] - THEN
PolarsErroris raised
Sampling rows
DataFrame SHALL support sample(n, withReplacement = false, shuffle = none(bool), seed = none(int)) and sample(fraction, ...) with the same options. shuffle SHALL also accept a plain bool: true shuffles the rows, false keeps their order and none gives no order guarantee, as in Polars. Asking for more rows than there are without replacement SHALL raise PolarsError. The same seed SHALL give the same rows. seed SHALL also accept a plain int (seed = 42), and setRandomSeed(seed) SHALL seed Polars' global generator, used when no seed is passed.
let df = newDataFrame(series("n", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
echo df.sample(3, seed = 42) == df.sample(3, seed = 42) # same seed, same rows
echo df.sample(fraction = 0.5).shape
setRandomSeed(42)
let a = df.sample(4)
setRandomSeed(42)
echo a == df.sample(4)
false
(5, 1)
false
- WHEN
sample(3, seed = some(42))runs twice on the same 10-row frame - THEN both results have 3 rows and are equal
- WHEN
setRandomSeed(42)is called before each of twosample(4)calls on the same frame - THEN both results are equal
- WHEN
sample(fraction = 0.5)runs on 10 rows - THEN the result has 5 rows
- WHEN
sample(11)runs on 10 rows - THEN
PolarsErroris raised
Every n-th row
LazyFrame and DataFrame SHALL support gatherEvery(n, offset = 0), keeping rows offset, offset + n, offset + 2n, ... (Python's gather_every).
let df = newDataFrame:
month: [1, 2, 3, 4, 5, 6]
echo df.gatherEvery(3, offset = 2)
shape: (2, 1)
┌───────┐
│ month │
│ --- │
│ i64 │
╞═══════╡
│ 3 │
│ 6 │
└───────┘
- WHEN
gatherEvery(2, offset = 10)runs on 6 rows - THEN the result has no rows
Frame interpolation
DataFrame and LazyFrame SHALL support interpolate(how = InterpolationMethod.Linear), filling the nulls of every column as Expr.interpolate does (Python's DataFrame.interpolate).
let df = newDataFrame:
day: [1, 2, 3]
temp: [some(-2.0), none(float), some(1.0)]
echo df.interpolate
shape: (3, 2)
┌─────┬──────┐
│ day ┆ temp │
│ --- ┆ --- │
│ f64 ┆ f64 │
╞═════╪══════╡
│ 1.0 ┆ -2.0 │
│ 2.0 ┆ -0.5 │
│ 3.0 ┆ 1.0 │
└─────┴──────┘
- WHEN an integer column with a null between 1 and 5 is interpolated
- THEN it becomes a float column holding 1.0, 3.0, 5.0
Casting by data type
DataFrame and LazyFrame cast SHALL also take a mapping from data types, or from selectors, to data types: cast({Float64: Float32}) casts every Float64 column, cast({col(SomeNumber): Float32}) every column the selector picks; other columns are kept.
let df = newDataFrame:
kg: [410.5, 380.0]
cubs: [1, 0]
bear: ["Ada", "Bo"]
echo df.cast({Float64: Float32}).schema
echo df.cast({col(SomeNumber): Float32}).schema
{"kg": Float32, "cubs": Int64, "bear": String}
{"kg": Float32, "cubs": Float32, "bear": String}
- WHEN
cast({Float64: Float32})runs on a frame with an Int64 column - THEN the Int64 column is unchanged
Several filter predicates
DataFrame and LazyFrame filter SHALL take several predicates, filter(a, b, ...), keeping the rows where all of them hold (Python's filter(a, b)).
let df = newDataFrame:
peak: ["Mont Blanc", "Monte Rosa", "Gran Paradiso"]
m: [4806, 4634, 4061]
italy: [true, true, true]
echo df.filter(col.m > 4500, col.italy)
shape: (2, 3)
┌────────────┬──────┬───────┐
│ peak ┆ m ┆ italy │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ bool │
╞════════════╪══════╪═══════╡
│ Mont Blanc ┆ 4806 ┆ true │
│ Monte Rosa ┆ 4634 ┆ true │
└────────────┴──────┴───────┘
- WHEN a row meets one predicate but not the other
- THEN it is dropped
Group order parameter
groupBy on DataFrame and LazyFrame SHALL accept maintainOrder (Python's maintain_order), with names or expressions; the groups SHALL keep the order their keys first appear whatever its value.
let df = newDataFrame:
country: ["CH", "IT", "CH"]
m: [4634, 4061, 4506]
echo df.groupBy("country", maintainOrder = true).agg(col.m.max)
shape: (2, 2)
┌─────────┬──────┐
│ country ┆ m │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════════╪══════╡
│ CH ┆ 4634 │
│ IT ┆ 4061 │
└─────────┴──────┘
- WHEN keys appear as CH, IT, CH and
maintainOrder = falseis passed - THEN the groups come out as CH, IT
Frame aggregations
DataFrames and LazyFrames SHALL provide sum, mean, median, product, min, max, std(ddof = 1), var(ddof = 1), quantile(q, interpolation), nUnique, count and nullCount(), each giving one row with the aggregation of every column; columns of a type the aggregation does not apply to (strings for sum) SHALL give null.
let df = newDataFrame(series("bear", @["Ada", "Bo", "Cy"]), series("kg", @[410, 380, 455]))
echo df.sum
echo df.max
echo df.nullCount
shape: (1, 2)
┌──────┬──────┐
│ bear ┆ kg │
│ --- ┆ --- │
│ str ┆ i64 │
╞══════╪══════╡
│ null ┆ 1245 │
└──────┴──────┘
shape: (1, 2)
┌──────┬─────┐
│ bear ┆ kg │
│ --- ┆ --- │
│ str ┆ i64 │
╞══════╪═════╡
│ Cy ┆ 455 │
└──────┴─────┘
shape: (1, 2)
┌──────┬─────┐
│ bear ┆ kg │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞══════╪═════╡
│ 0 ┆ 0 │
└──────┴─────┘
- WHEN
df.lazy.mean.collectruns - THEN it equals
df.mean
Group-by shortcuts
GroupBy and LazyGroupBy SHALL provide len(name = "len"), count, head(n = 5), tail(n = 5), first, last, sum, mean, median, min, max, nUnique, quantile(q) and all, each aggregating every non-key column per group, with groups in order of appearance.
let df = newDataFrame(series("den", @["N", "S", "N"]), series("kg", @[410, 380, 455]))
echo df.groupBy("den").max
echo df.groupBy("den").len
echo df.groupBy("den").head(1)
shape: (2, 2)
┌─────┬─────┐
│ den ┆ kg │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ N ┆ 455 │
│ S ┆ 380 │
└─────┴─────┘
shape: (2, 2)
┌─────┬─────┐
│ den ┆ len │
│ --- ┆ --- │
│ str ┆ u32 │
╞═════╪═════╡
│ N ┆ 2 │
│ S ┆ 1 │
└─────┴─────┘
shape: (2, 2)
┌─────┬─────┐
│ den ┆ kg │
│ --- ┆ --- │
│ str ┆ i64 │
╞═════╪═════╡
│ N ┆ 410 │
│ S ┆ 380 │
└─────┴─────┘
- WHEN
headis called on agroupByDynamic - THEN
InvalidOperationErroris raised
Iterating over groups
for key, part in df.groupBy(columns) SHALL yield each group's key values (as strings, in by order) and its rows, groups in order of appearance.
let df = newDataFrame(series("den", @["N", "S", "N"]), series("kg", @[410, 380, 455]))
for key, part in df.groupBy("den"):
echo key, " ", part.height
@["N"] 2
@["S"] 1
- WHEN a frame is grouped by two columns and iterated
- THEN each key holds two values
Frame fillNan and select without a frame
fillNan(value) on DataFrames and LazyFrames SHALL replace NaN in float columns (nil for null), and select(exprs...) SHALL evaluate expressions without a frame.
echo newDataFrame(series("x", @[1.0, NaN])).fillNan(0.0)
echo select(lit(1).alias("one"), intRange(0, 3).alias("i"))
shape: (2, 1)
┌─────┐
│ x │
│ --- │
│ f64 │
╞═════╡
│ 1.0 │
│ 0.0 │
└─────┘
shape: (3, 2)
┌─────┬─────┐
│ one ┆ i │
│ --- ┆ --- │
│ i32 ┆ i64 │
╞═════╪═════╡
│ 1 ┆ 0 │
│ 1 ┆ 1 │
│ 1 ┆ 2 │
└─────┴─────┘
- WHEN a frame with an integer and a float column gets
fillNan(0.0) - THEN the integer column is unchanged
horizontal-functions
Purpose: Functions that compute across the columns of a row, columns generated from ranges and repeated values, and correlation between columns.
Horizontal functions
sumHorizontal, meanHorizontal, minHorizontal, maxHorizontal, allHorizontal, anyHorizontal and coalesce SHALL compute row by row over their arguments, which SHALL be expressions, literals, selectors (expanded to their columns) or a list of column names. sumHorizontal and meanHorizontal SHALL skip nulls unless ignoreNulls = false, and coalesce SHALL return the first non-null value.
let df = newDataFrame:
station: ["Lima", "Piura", "Tumbes"]
jan: [1.0, 4.0, nil]
feb: [2.0, 30.0, 61.0]
mar: [1.0, 80.0, 95.0]
echo df.select(col.station, sumHorizontal(col(float)).alias("total"),
maxHorizontal("jan", "feb", "mar").alias("wettest"),
coalesce(col.jan, col.feb).alias("first_reading"))
shape: (3, 4)
┌─────────┬───────┬─────────┬───────────────┐
│ station ┆ total ┆ wettest ┆ first_reading │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ str ┆ f64 │
╞═════════╪═══════╪═════════╪═══════════════╡
│ Lima ┆ 4.0 ┆ mar ┆ 1.0 │
│ Piura ┆ 114.0 ┆ mar ┆ 4.0 │
│ Tumbes ┆ 156.0 ┆ mar ┆ 61.0 │
└─────────┴───────┴─────────┴───────────────┘
- WHEN
sumHorizontal([col.a, col.b], ignoreNulls = false)runs on a row wherebis null - THEN that row's sum is null
- WHEN
allHorizontalandanyHorizontalrun on a row holding true and false - THEN they give false and true
Generated columns
intRange(start, stop, step = 1, dtype = Int64) (or intRange(stop)) SHALL produce the integers from start up to stop excluded, linearSpace(start, stop, numSamples, closed) SHALL produce evenly spaced floats, and repeat(value, n) SHALL repeat a value n times. A string value SHALL be wrapped in lit, since std/strutils' repeat takes plain strings.
echo newDataFrame().select(intRange(1950, 2026, 25).alias("year"),
linearSpace(0, 1, 4).alias("share"),
repeat(lit("ENSO"), 4).alias("index"))
shape: (4, 3)
┌──────┬──────────┬───────┐
│ year ┆ share ┆ index │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str │
╞══════╪══════════╪═══════╡
│ 1950 ┆ 0.0 ┆ ENSO │
│ 1975 ┆ 0.333333 ┆ ENSO │
│ 2000 ┆ 0.666667 ┆ ENSO │
│ 2025 ┆ 1.0 ┆ ENSO │
└──────┴──────────┴───────┘
- WHEN
intRange(0, 5, step = 0)is built - THEN
ValueErroris raised
Correlation
corr(a, b, how = Pearson) SHALL return the Pearson or Spearman correlation of two columns as an aggregation, and cov(a, b, ddof = 1) their covariance.
let df = newDataFrame:
oni: [-1.0, 0.0, 0.5, 2.0]
world: [14.6, 14.8, 14.9, 15.2]
echo df.select(corr("oni", "world").round(3).alias("pearson"),
corr("oni", "world", how = Spearman).alias("spearman"))
shape: (1, 2)
┌─────────┬──────────┐
│ pearson ┆ spearman │
│ --- ┆ --- │
│ f64 ┆ f64 │
╞═════════╪══════════╡
│ 1.0 ┆ 1.0 │
└─────────┴──────────┘
- WHEN
corrruns on 1, 2, 3 and 2, 4, 6 - THEN the result is 1.0
inspection
Purpose: Looking at a frame: glimpse, describe, and the display configuration (setTbl*, setConfig, withConfig).
glimpse
glimpse(df, maxItemsPerColumn = 10, maxColnameLength = 50) SHALL return, as a string, the lines Rows: <height> and Columns: <width>, then one line per column: $ <name> <<dtype>> <values>, with names left-aligned and dtypes right-aligned to a common width, and the first maxItemsPerColumn values joined by ", ". Nulls SHALL be null, booleans True/False, and strings quoted as Python's repr quotes them. Names longer than maxColnameLength SHALL be cut and end with ….
let df = newDataFrame:
rider: ["Pogačar", "Seixas", "Van der Poel"]
wins: [22, 8, nil]
pro: [true, false, true]
race: ["Giro d'Italia", "Tour", "Vuelta"]
echo df.glimpse
Rows: 3
Columns: 4
$ rider <str> 'Pogačar', 'Seixas', 'Van der Poel'
$ wins <i64> 22, 8, null
$ pro <bool> True, False, True
$ race <str> "Giro d'Italia", 'Tour', 'Vuelta'
- WHEN a column of 100 rows is glimpsed with
maxItemsPerColumn = 3 - THEN its line shows the first 3 values only
- WHEN a column named with 60 characters is glimpsed
- THEN its line shows the first 49 characters followed by
…
describe
describe(percentiles = [0.25, 0.5, 0.75], interpolation = Nearest) on DataFrame and LazyFrame SHALL return a DataFrame with a statistic column holding count, null_count, mean, std, min, one row per percentile (labelled as 25%) and max, followed by one column per input column: f64 for numeric and boolean columns, str for the others, and null where a statistic does not apply.
let df = newDataFrame:
rider: ["Pogačar", "Seixas", "Van der Poel"]
wins: [22, 8, nil]
pro: [true, false, true]
echo df.describe
shape: (9, 4)
┌────────────┬──────────────┬──────────┬──────────┐
│ statistic ┆ rider ┆ wins ┆ pro │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ f64 ┆ f64 │
╞════════════╪══════════════╪══════════╪══════════╡
│ count ┆ 3 ┆ 2.0 ┆ 3.0 │
│ null_count ┆ 0 ┆ 1.0 ┆ 0.0 │
│ mean ┆ null ┆ 15.0 ┆ 0.666667 │
│ std ┆ null ┆ 9.899495 ┆ null │
│ min ┆ Pogačar ┆ 8.0 ┆ 0.0 │
│ 25% ┆ null ┆ 8.0 ┆ null │
│ 50% ┆ null ┆ 22.0 ┆ null │
│ 75% ┆ null ┆ 22.0 ┆ null │
│ max ┆ Van der Poel ┆ 22.0 ┆ 1.0 │
└────────────┴──────────────┴──────────┴──────────┘
- WHEN
describe(percentiles = [0.1, 0.9])runs - THEN the statistic column holds
count,null_count,mean,std,min,10%,90%andmax
- WHEN a frame with a string and a boolean column is described
- THEN mean, std and percentiles are null for the string column, and std and percentiles for the boolean one
- WHEN
newDataFrame().describeruns - THEN
PolarsErroris raised
Display config
The API SHALL set how tables print with setTblRows(n), setTblCols(n), setTblWidthChars(n) and setFmtStrLengths(n), where -1 means no limit and none(int) restores Polars' default; with setFloatPrecision(n), the number of decimal places floats print with (none(int) for Polars' default); with setConfig(tblRows, tblCols, tblWidthChars, fmtStrLengths, floatPrecision), where options left out are unchanged; and with resetConfig(), which restores every default. The settings SHALL apply to every later $ of a DataFrame.
let df = newDataFrame(series("n", [1, 2, 3, 4, 5, 6]))
setTblRows(4); setFmtStrLengths(10)
echo df
setConfig(tblRows = 2, tblCols = 5)
echo df
resetConfig()
shape: (6, 1)
┌─────┐
│ n │
│ --- │
│ i64 │
╞═════╡
│ 1 │
│ 2 │
│ … │
│ 5 │
│ 6 │
└─────┘
shape: (6, 1)
┌─────┐
│ n │
│ --- │
│ i64 │
╞═════╡
│ 1 │
│ … │
│ 6 │
└─────┘
- WHEN
setConfig(floatPrecision = 2)is called and a frame holding 0.05333 prints - THEN the value shows as 0.05
- WHEN
setTblRows(-1)is called and a frame of 50 rows is printed - THEN all 50 rows are shown
- WHEN
setTblRows(2)and thenresetConfig()are called - THEN a frame of 10 rows prints all 10 rows again
Scoped display config
withConfig(options): body SHALL apply the named options (tblRows, tblCols, tblWidthChars, fmtStrLengths, floatPrecision) while body runs, and SHALL restore the previous settings afterwards, also when body raises.
let df = newDataFrame(series("n", [1, 2, 3, 4, 5, 6]))
withConfig(tblRows = 2):
echo df
echo df.shape, " ", ($df).count('\n')
shape: (6, 1)
┌─────┐
│ n │
│ --- │
│ i64 │
╞═════╡
│ 1 │
│ … │
│ 6 │
└─────┘
(6, 1) 12
- WHEN the body of
withConfig(tblRows = 2)raises - THEN the exception propagates and the row limit is back to its previous value
Describe prints temporal values as Python
describe SHALL print Datetime statistics and the mean of a Date column as YYYY-MM-DD HH:MM:SS, with a fraction only when it is not zero.
let df = newDataFrame(series("d", @[date(1986, 9, 1), date(1986, 9, 7)]))
echo df.describe
shape: (9, 2)
┌────────────┬─────────────────────┐
│ statistic ┆ d │
│ --- ┆ --- │
│ str ┆ str │
╞════════════╪═════════════════════╡
│ count ┆ 2 │
│ null_count ┆ 0 │
│ mean ┆ 1986-09-04 00:00:00 │
│ std ┆ null │
│ min ┆ 1986-09-01 │
│ 25% ┆ 1986-09-01 │
│ 50% ┆ 1986-09-07 │
│ 75% ┆ 1986-09-07 │
│ max ┆ 1986-09-07 │
└────────────┴─────────────────────┘
- WHEN the mean of 1986-09-01 and 1986-09-07 is described
- THEN it reads
1986-09-04 00:00:00
Table formatting options
setTblFormatting(TableFormat, roundedCorners), setAsciiTables, setTblHideColumnDataTypes, setTblHideColumnNames, setTblHideDataframeShape, setTblHideColumnSeparator, setTblDataframeShapeBelow, setTblColumnDataTypeInline, setTblCellAlignment, setTblCellNumericAlignment and setFmtTableCellListLen SHALL change how frames print; setConfig and withConfig SHALL take tblFormatting, asciiTables, tblHideColumnDataTypes, tblHideColumnNames, tblHideDataframeShape and tblCellAlignment, and resetConfig SHALL undo them all.
let df = newDataFrame(series("bear", @["Ada"]), series("kg", @[410]))
withConfig(tblFormatting = TableFormat.Markdown, tblHideDataframeShape = true):
echo df
| bear | kg |
| --- | --- |
| str | i64 |
|------|-----|
| Ada | 410 |
- WHEN a frame prints inside
withConfig(asciiTables = true) - THEN its borders use
+,-and|
json-io
Purpose: Reading and writing JSON and NDJSON.
Reading JSON
readJson(source) SHALL read a JSON array of objects (one row each) from a file path or a Stream, and readNdjson(source) newline-delimited JSON, with nested values becoming List and Struct columns. schema SHALL fix all column types, schemaOverrides some of them, inferSchemaLength SHALL bound the rows used to infer the rest, and ignoreErrors SHALL read values that do not parse as null.
import std/streams
let json = """[{"bear": "Ada", "cubs": ["Bo"], "den": {"lat": 78.2}},
{"bear": "Cy", "cubs": [], "den": {"lat": 79.0}}]"""
let df = readJson(newStringStream(json))
echo df
echo readNdjson(newStringStream("{\"a\": 1}\n{\"a\": 2}\n"), schemaOverrides = {"a": Float64})
shape: (2, 3)
┌──────┬───────────┬───────────┐
│ bear ┆ cubs ┆ den │
│ --- ┆ --- ┆ --- │
│ str ┆ list[str] ┆ struct[1] │
╞══════╪═══════════╪═══════════╡
│ Ada ┆ ["Bo"] ┆ {78.2} │
│ Cy ┆ [] ┆ {79.0} │
└──────┴───────────┴───────────┘
shape: (2, 1)
┌─────┐
│ a │
│ --- │
│ f64 │
╞═════╡
│ 1.0 │
│ 2.0 │
└─────┘
- WHEN a file that is not JSON is read with
readJson - THEN
ComputeErroris raised
Scanning NDJSON
scanNdjson(path) SHALL read newline-delimited JSON files lazily (a path or a glob), with nRows, rowIndexName and rowIndexOffset and the schema options of readNdjson.
let path = getTempDir() / "bears.ndjson"
writeFile(path, "{\"bear\": \"Ada\", \"kg\": 410}\n{\"bear\": \"Bo\", \"kg\": 380}\n")
echo scanNdjson(path, rowIndexName = "i").filter(col("kg") > 400).collect
shape: (1, 3)
┌─────┬──────┬─────┐
│ i ┆ bear ┆ kg │
│ --- ┆ --- ┆ --- │
│ u32 ┆ str ┆ i64 │
╞═════╪══════╪═════╡
│ 0 ┆ Ada ┆ 410 │
└─────┴──────┴─────┘
- WHEN a file of 3 lines is scanned with
nRows = 2 - THEN the frame has 2 rows
Writing JSON
writeJson(dest) SHALL write a frame as a JSON array of row objects to a path or a Stream, writeNdjson(dest) one object per line, and toJson/toNdjson SHALL return the same text; reading it back SHALL give the same frame.
let df = newDataFrame:
bear: ["Ada", "Bo"]
cubs: [@["Cy"], @[]]
echo df.toJson
echo df.toNdjson
[{"bear":"Ada","cubs":["Cy"]},{"bear":"Bo","cubs":[]}]
{"bear":"Ada","cubs":["Cy"]}
{"bear":"Bo","cubs":[]}
- WHEN a frame with list and struct columns is written with
writeNdjsonand read withreadNdjson - THEN the result equals the frame
list-functions
Purpose: Functions on list columns: the list namespace, explode, implode and concatList.
List aggregations and access
e.list SHALL give a namespace whose methods work on each list of a List (or Array) column: len, sum, min, max, mean, median, std, var, first, last, argMin, argMax, nUnique, any, all give one value per list; get(i) (negative from the end), gather, gatherEvery, slice, head, tail pick values; contains(x), countMatches(x) and join(separator) compare or join them.
let df = newDataFrame:
cubs: [@[2, 1, 3], @[], @[4]]
names: [@["Ada", "Bo"], @["Cy"], @[]]
echo df.select(col("cubs").list.len.alias("n"), col("cubs").list.sum.alias("sum"),
col("cubs").list.get(0, nullOnOob = true).alias("first"),
col("cubs").list.contains(3).alias("has3"),
col("names").list.join(", ").alias("names"))
shape: (3, 5)
┌─────┬─────┬───────┬───────┬─────────┐
│ n ┆ sum ┆ first ┆ has3 ┆ names │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ u32 ┆ i64 ┆ i64 ┆ bool ┆ str │
╞═════╪═════╪═══════╪═══════╪═════════╡
│ 3 ┆ 6 ┆ 2 ┆ true ┆ Ada, Bo │
│ 0 ┆ 0 ┆ null ┆ false ┆ Cy │
│ 1 ┆ 4 ┆ 4 ┆ false ┆ │
└─────┴─────┴───────┴───────┴─────────┘
- WHEN
list.get(5)is evaluated on a list of 3 values withoutnullOnOob - THEN
ComputeErroris raised; withnullOnOob = truethe value is null
List transforms
e.list SHALL have sort, reverse, unique, dropNulls, diff, shift, sample, filter(predicate), the set operations union, setDifference, setIntersection and setSymmetricDifference with another list expression, toArray(width) and toStruct(fields), each giving a list (array or struct) per row.
let df = newDataFrame:
a: [@[3, 1, 3], @[2]]
b: [@[1, 5], @[2, 4]]
echo df.select(col("a").list.sort.alias("sorted"), col("a").list.unique(maintainOrder = true).alias("unique"),
col("a").list.union(col("b")).alias("union"),
col("a").list.filter(element() > 1).alias("gt1"))
shape: (2, 4)
┌───────────┬───────────┬───────────┬───────────┐
│ sorted ┆ unique ┆ union ┆ gt1 │
│ --- ┆ --- ┆ --- ┆ --- │
│ list[i64] ┆ list[i64] ┆ list[i64] ┆ list[i64] │
╞═══════════╪═══════════╪═══════════╪═══════════╡
│ [1, 3, 3] ┆ [3, 1] ┆ [3, 1, 5] ┆ [3, 3] │
│ [2] ┆ [2] ┆ [2, 4] ┆ [2] │
└───────────┴───────────┴───────────┴───────────┘
- WHEN
list.toStruct(["x", "y"])is evaluated on lists of two values - THEN the result is a struct column with fields
xandy
Expressions on list elements
list.eval(e) SHALL evaluate e on the values of each list, with element() standing for them, and give a list per row; list.agg(e) SHALL do the same for an aggregation and give one value per row.
let df = newDataFrame:
weights: [@[410.0, 380.0], @[450.0, 470.0, 455.0]]
echo df.select(col("weights").list.eval(element().rank).alias("rank"),
col("weights").list.agg(element().max - element().min).alias("spread"))
shape: (2, 2)
┌─────────────────┬────────┐
│ rank ┆ spread │
│ --- ┆ --- │
│ list[f64] ┆ f64 │
╞═════════════════╪════════╡
│ [2.0, 1.0] ┆ 30.0 │
│ [1.0, 3.0, 2.0] ┆ 20.0 │
└─────────────────┴────────┘
- WHEN
element()is used in aselectthat is not insidelist.eval - THEN evaluating it raises a Polars error
Explode and implode
e.explode and e.list.explode SHALL give one row per list value, df.explode(columns) SHALL do the same for whole rows (eager and lazy; emptyAsNull and keepNulls default to true, as in Polars), e.implode SHALL collect a column into one list, and concatList(exprs) SHALL join values and lists of several columns into one list per row.
let df = newDataFrame:
den: ["A", "B", "C"]
cubs: [@["Ada", "Bo"], @[], @["Cy"]]
echo df.explode("cubs")
echo df.select(concatList(col("den"), col("cubs")).alias("all"))
echo df.select(col("den").implode)
shape: (4, 2)
┌─────┬──────┐
│ den ┆ cubs │
│ --- ┆ --- │
│ str ┆ str │
╞═════╪══════╡
│ A ┆ Ada │
│ A ┆ Bo │
│ B ┆ null │
│ C ┆ Cy │
└─────┴──────┘
shape: (3, 1)
┌────────────────────┐
│ all │
│ --- │
│ list[str] │
╞════════════════════╡
│ ["A", "Ada", "Bo"] │
│ ["B"] │
│ ["C", "Cy"] │
└────────────────────┘
shape: (1, 1)
┌─────────────────┐
│ den │
│ --- │
│ list[str] │
╞═════════════════╡
│ ["A", "B", "C"] │
└─────────────────┘
- WHEN a frame with an empty list is exploded with
emptyAsNull = false - THEN that row is dropped instead of giving a null
Exploding several columns by name
DataFrame and LazyFrame explode SHALL also take several column names as separate arguments: explode("a", "b") is explode(["a", "b"]).
let df = newDataFrame:
peak: ["Mont Blanc", "Monte Rosa"]
huts: [@["Goûter", "Cosmiques"], @["Margherita", "Gnifetti"]]
m: [@[3835, 3613], @[4554, 3647]]
echo df.explode("huts", "m")
shape: (4, 3)
┌────────────┬────────────┬──────┐
│ peak ┆ huts ┆ m │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 │
╞════════════╪════════════╪══════╡
│ Mont Blanc ┆ Goûter ┆ 3835 │
│ Mont Blanc ┆ Cosmiques ┆ 3613 │
│ Monte Rosa ┆ Margherita ┆ 4554 │
│ Monte Rosa ┆ Gnifetti ┆ 3647 │
└────────────┴────────────┴──────┘
- WHEN two list columns with lists of the same lengths are exploded together
- THEN each row holds the matching elements of both
Repeating values into lists
Expr.repeatBy(by) SHALL repeat each value by times into a list, where by is an int, a column name or an expression (Python's repeat_by).
let df = newDataFrame:
hut: ["Goûter", "Margherita"]
nights: [2, 1]
echo df.select(col.hut.repeatBy("nights"))
shape: (2, 1)
┌──────────────────────┐
│ hut │
│ --- │
│ list[str] │
╞══════════════════════╡
│ ["Goûter", "Goûter"] │
│ ["Margherita"] │
└──────────────────────┘
- WHEN
repeatBy(2)runs on "x" - THEN the result is the list
["x", "x"]
Seeds as plain ints
sample on expressions and on list SHALL take the seed as a plain int, sample(3, seed = 42), as shuffle and frame sample do; the same seed SHALL give the same values.
let df = newDataFrame:
m: [4806, 4634, 4061, 4506, 4478]
echo df.select(col.m.sample(3, seed = 42)).height
3
- WHEN
sample(3, seed = 42)runs twice on the same column - THEN both runs give the same values
math-functions
Purpose: Elementwise math on expressions: roots, exponentials and logarithms, rounding to integers, clipping, trigonometry, the dot product, and NaN and infinity, which Polars keeps apart from null.
Elementwise math
Expressions SHALL have sqrt, cbrt, exp, log(base = E), log10, log1p, sign, floor and ceil, computed value by value as in Polars, with nulls staying null. sqrt, cbrt, exp and the logarithms SHALL return Float64 for integer input.
let df = newDataFrame:
x: [1.0, 4.0, 10.0, nil]
echo df.select(col.x.sqrt.alias("sqrt"), col.x.log10.alias("log10"),
col.x.log(2.0).alias("log2"), col.x.exp.round(1).alias("exp"))
shape: (4, 4)
┌──────────┬─────────┬──────────┬─────────┐
│ sqrt ┆ log10 ┆ log2 ┆ exp │
│ --- ┆ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ f64 ┆ f64 │
╞══════════╪═════════╪══════════╪═════════╡
│ 1.0 ┆ 0.0 ┆ 0.0 ┆ 2.7 │
│ 2.0 ┆ 0.60206 ┆ 2.0 ┆ 54.6 │
│ 3.162278 ┆ 1.0 ┆ 3.321928 ┆ 22026.5 │
│ null ┆ null ┆ null ┆ null │
└──────────┴─────────┴──────────┴─────────┘
- WHEN
sqrtruns on an Int64 column holding 4 and 9 - THEN the result is a Float64 column holding 2.0 and 3.0
- WHEN
sign,floorandceilrun on -2.5 and 1.5 - THEN they give -1 and 1, -3.0 and 1.0, -2.0 and 2.0
Clipping
clip(lowerBound, upperBound) SHALL limit values to the range, and clip(lowerBound = v) or clip(upperBound = v) SHALL limit them on one side. Bounds SHALL be literals or expressions.
let df = newDataFrame:
anomaly: [-2.1, -0.3, 0.4, 2.6]
echo df.select(col.anomaly.clip(-1.0, 1.0).alias("both"),
col.anomaly.clip(lowerBound = 0.0).alias("warm_only"))
shape: (4, 2)
┌──────┬───────────┐
│ both ┆ warm_only │
│ --- ┆ --- │
│ f64 ┆ f64 │
╞══════╪═══════════╡
│ -1.0 ┆ 0.0 │
│ -0.3 ┆ 0.0 │
│ 0.4 ┆ 0.4 │
│ 1.0 ┆ 2.6 │
└──────┴───────────┘
- WHEN
clip(-1.0, 1.0)runs on -2.1 and 2.6 - THEN the result is -1.0 and 1.0
Trigonometry
Expressions SHALL have sin, cos, tan, cot, arcsin, arccos, arctan, sinh, cosh, tanh, arcsinh, arccosh, arctanh, degrees and radians, working in radians, and arctan2(y, x) SHALL return the angle of the point (x, y).
let df = newDataFrame:
deg: [0.0, 90.0, 180.0]
echo df.select(col.deg.radians.sin.round(3).alias("sin"),
arctan2(lit(1.0), lit(1.0)).degrees.alias("atan2"))
shape: (3, 2)
┌─────┬───────┐
│ sin ┆ atan2 │
│ --- ┆ --- │
│ f64 ┆ f64 │
╞═════╪═══════╡
│ 0.0 ┆ 45.0 │
│ 1.0 ┆ 45.0 │
│ 0.0 ┆ 45.0 │
└─────┴───────┘
- WHEN
radiansand thendegreesrun on 90.0 - THEN the result is 90.0
NaN and infinity
isNan, isNotNan, isFinite and isInfinite SHALL test float values (nulls give null), fillNan(value) SHALL replace NaN with a literal or expression, dropNans SHALL remove NaN values and Expr.dropNulls SHALL remove nulls. NaN SHALL stay distinct from null, as in Polars.
import std/math
let df = newDataFrame:
x: [1.0, NaN, Inf, nil]
echo df.select(col.x.isNan.alias("nan"), col.x.isFinite.alias("finite"),
col.x.fillNan(0.0).alias("filled"))
echo df.select(col.x.dropNans.dropNulls)
shape: (4, 3)
┌───────┬────────┬────────┐
│ nan ┆ finite ┆ filled │
│ --- ┆ --- ┆ --- │
│ bool ┆ bool ┆ f64 │
╞═══════╪════════╪════════╡
│ false ┆ true ┆ 1.0 │
│ true ┆ false ┆ 0.0 │
│ false ┆ false ┆ inf │
│ null ┆ null ┆ null │
└───────┴────────┴────────┘
shape: (2, 1)
┌─────┐
│ x │
│ --- │
│ f64 │
╞═════╡
│ 1.0 │
│ inf │
└─────┘
- WHEN
isNullruns on a column holding NaN - THEN the result is false
- WHEN
fillNan(0.0)runs on NaN and null - THEN the result is 0.0 and null
Dot product
a.dot(b) SHALL return the sum of the elementwise products of two columns, as an aggregation.
let df = newDataFrame:
a: [1, 2, 3]
b: [4, 5, 6]
echo df.select(col.a.dot(col.b))
shape: (1, 1)
┌─────┐
│ a │
│ --- │
│ i64 │
╞═════╡
│ 32 │
└─────┘
- WHEN
col.a.dot(col.b)runs on a = 1, 2, 3 and b = 4, 5, 6 - THEN the result is one row holding 32
missing-values
Purpose: How Nanuq represents missing values (Polars nulls) in its Nim API: building data with gaps, reading it back, and testing, filling and dropping nulls in queries.
Nulls are read as Option
Reading a column or a cell with the type Option[T] SHALL return none(T) for each null and some(value) otherwise, for T in int, float, bool and string.
let df = newDataFrame(series("a", [some(1), none(int), some(3)]))
echo df.toList("a", Option[int])
echo df["a", 1, Option[int]]
@[some(1), none(int), some(3)]
none(int)
- WHEN a column holds 1, null, 3 and is read with
toList(df, "a", Option[int]) - THEN the result is
@[some(1), none(int), some(3)]
- WHEN the null cell is read with
df["a", 1, Option[int]] - THEN the result is
none(int)
Plain reads refuse nulls
Reading a column or a cell with a plain type T SHALL raise InvalidOperationError if the values read include a null, and the message SHALL name the column.
let df = newDataFrame(series("a", [some(1), none(int)]))
try:
discard df.toList("a", int)
except PolarsError as e:
echo e.name
InvalidOperationError
- WHEN a column with one null is read with
toList(df, "a", int) - THEN
InvalidOperationErroris raised before any value is returned, naming column "a"
Inspecting nulls
The API SHALL report the number of nulls in a column and whether it has any, and SHALL provide nullCount on expressions as an aggregation (u32), usable in select and agg.
let df = newDataFrame(series("a", [some(1), none(int), some(3)]))
echo df.nullCount("a"), " ", df.hasNulls("a")
echo df.select(col.a.nullCount.alias("missing"))
1 true
shape: (1, 1)
┌─────────┐
│ missing │
│ --- │
│ u32 │
╞═════════╡
│ 1 │
└─────────┘
- WHEN a column of 3 values has 1 null
- THEN
nullCount(df, "a")is 1 andhasNulls(df, "a")is true
- WHEN a column has no nulls
- THEN
nullCountis 0 andhasNullsis false
- WHEN
groupBy(col.g).agg(col.a.nullCount)runs on groups with 1 and 0 nulls - THEN the result has 1 and 0 for those groups
Building columns with nulls
series SHALL accept openArray[Option[T]] for int, float, bool and string, storing none as null with the same dtype as the plain version.
let df = newDataFrame(series("a", [some(1), none(int)]), series("s", [none(string), some("x")]))
echo df
shape: (2, 2)
┌──────┬──────┐
│ a ┆ s │
│ --- ┆ --- │
│ i64 ┆ str │
╞══════╪══════╡
│ 1 ┆ null │
│ null ┆ x │
└──────┴──────┘
- WHEN a DataFrame is built from
series("a", [some(1), none(int)]) - THEN
dtype(df, "a")is "i64",nullCount(df, "a")is 1, and reading it asOption[int]gives back the input
CSV null markers
readCsv SHALL accept a list of strings to read as null. Without it, behavior is unchanged: only empty fields are null.
let path = getTempDir() / "bears.csv"
writeFile(path, "bear,weight\nNanuq,410\nUrsa,NA\n")
echo readCsv(path, nullValues = ["NA"])
shape: (2, 2)
┌───────┬────────┐
│ bear ┆ weight │
│ --- ┆ --- │
│ str ┆ i64 │
╞═══════╪════════╡
│ Nanuq ┆ 410 │
│ Ursa ┆ null │
└───────┴────────┘
- WHEN a CSV file with "NA" in a numeric column is read with
nullValues = @["NA"] - THEN that column is numeric and the "NA" fields are null
Null expressions
The API SHALL provide isNull and isNotNull on expressions (giving booleans), and fillNull replacing nulls with a literal or an expression.
let df = newDataFrame(series("a", [some(1), none(int), some(3)]))
echo df.select(col("a").isNull.alias("missing"), col("a").fillNull(0).alias("filled"))
echo df.filter(col("a").isNotNull).toList("a", int)
shape: (3, 2)
┌─────────┬────────┐
│ missing ┆ filled │
│ --- ┆ --- │
│ bool ┆ i64 │
╞═════════╪════════╡
│ false ┆ 1 │
│ true ┆ 0 │
│ false ┆ 3 │
└─────────┴────────┘
@[1, 3]
- WHEN a LazyFrame is filtered with
col("a").isNotNulland collected - THEN the result has no nulls in column "a"
- WHEN
withColumns(col("a").fillNull(0))is applied to a column 1, null, 3 - THEN column "a" becomes 1, 0, 3
Dropping rows with nulls
LazyFrame and DataFrame SHALL provide dropNulls, removing rows with a null in any column, or only in the named columns when a subset is given.
let df = newDataFrame(series("a", [some(1), none(int), some(3)]),
series("b", [some("x"), some("y"), none(string)]))
echo df.dropNulls.shape # any column
echo df.dropNulls("a") # only column a
(1, 2)
shape: (2, 2)
┌─────┬──────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ str │
╞═════╪══════╡
│ 1 ┆ x │
│ 3 ┆ null │
└─────┴──────┘
- WHEN
dropNulls(["a"])is applied to rows where "a" has one null and "b" another, in different rows - THEN only the row with the null in "a" is removed
Interpolation
e.interpolate() SHALL fill nulls that lie between two values on a straight line between them, or with the nearest value for interpolate(how = Nearest); e.interpolateBy(by) SHALL interpolate linearly using the distances in column by. Nulls before the first and after the last value SHALL stay null.
let df = newDataFrame:
day: [1, 2, 4, 5]
temp: [10.0, nil, 16.0, nil]
echo df.withColumns(col.temp.interpolate.alias("linear"),
col.temp.interpolateBy("day").alias("by_day"))
shape: (4, 4)
┌─────┬──────┬────────┬────────┐
│ day ┆ temp ┆ linear ┆ by_day │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 ┆ f64 │
╞═════╪══════╪════════╪════════╡
│ 1 ┆ 10.0 ┆ 10.0 ┆ 10.0 │
│ 2 ┆ null ┆ 13.0 ┆ 12.0 │
│ 4 ┆ 16.0 ┆ 16.0 ┆ 16.0 │
│ 5 ┆ null ┆ null ┆ null │
└─────┴──────┴────────┴────────┘
- WHEN
interpolateruns on 1, null, 3 - THEN the result is 1.0, 2.0, 3.0
Null literal
lit(nil) SHALL be a null literal (Python's pl.lit(None)), usable wherever an expression is, and fillNan(nil) SHALL turn NaN values into nulls.
let df = newDataFrame:
x: [1.0, NaN, 3.0]
echo df.select(col.x.fillNan(nil).alias("x"), col.x.fillNan(nil).nullCount.alias("nulls"))
shape: (3, 2)
┌──────┬───────┐
│ x ┆ nulls │
│ --- ┆ --- │
│ f64 ┆ u32 │
╞══════╪═══════╡
│ 1.0 ┆ 1 │
│ null ┆ 1 │
│ 3.0 ┆ 1 │
└──────┴───────┘
- WHEN
select(lit(nil).alias("n"))runs with another column of 3 rows - THEN
nholds 3 nulls
Filling nulls in whole frames
DataFrame and LazyFrame SHALL support fillNull(value), filling the columns the value fits (a number: numeric columns, where a float turns integer columns into Float64; a string: String columns; a bool: Boolean columns), and fillNull(strategy, limit) on every column (Python's df.fill_null).
let df = newDataFrame:
peak: ["Dom", "Täschhorn"]
m: [some(4545), none(int)]
first_ascent: [some(1858), none(int)]
echo df.fillNull(0)
shape: (2, 3)
┌───────────┬──────┬──────────────┐
│ peak ┆ m ┆ first_ascent │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═══════════╪══════╪══════════════╡
│ Dom ┆ 4545 ┆ 1858 │
│ Täschhorn ┆ 0 ┆ 0 │
└───────────┴──────┴──────────────┘
- WHEN
fillNull(0.5)runs on a frame with an Int64 column with nulls - THEN that column becomes Float64 and its nulls hold 0.5
- WHEN
fillNull("x")runs on a frame with Int64 and String columns - THEN only the String column is filled
native-bridge
Purpose: How Nanuq reaches Polars: a Rust crate (rust/, nanuq_ffi) exports a C ABI, it is
linked as a static library, and src/nanuq/ffi.nim declares it to Nim.
C ABI over Polars with opaque handles
The nanuq_ffi crate SHALL expose Polars objects (DataFrame, LazyFrame, Expr, Series) only as opaque heap pointers through extern "C" functions, each type with a matching *_free function. Functions SHALL borrow their pointer arguments and return newly allocated objects.
- WHEN Nim passes a DataFrame pointer to an FFI function
- THEN the pointer stays valid and owned by Nim after the call
- AND any object the function returns is a new pointer that Nim must free exactly once
Errors and panics never cross the boundary
Every FFI function SHALL catch Polars errors and Rust panics, signal failure with a NULL (or false / -1) return, and make the message available through nq_last_error and its kind through nq_last_error_kind.
- WHEN an operation fails in Polars (e.g. a missing column)
- THEN the function returns NULL and
nq_last_errorreturns the Polars message
- WHEN Polars panics inside an FFI call
- THEN the panic is caught, the call returns NULL, and no unwinding reaches Nim
- WHEN an operation fails with a Polars
ColumnNotFounderror, possibly wrapped in context - THEN
nq_last_error_kindreturnsColumnNotFound
Nim declarations mirror the C ABI
src/nanuq/ffi.nim SHALL declare every exported function with matching signatures, and the enums NqBinOp, NqUnary, NqDtype, NqDtypeClass, NqJoinType, NqJoinValidation, NqMaintainOrderJoin, NqConcat, NqUniqueKeepStrategy, NqClosedInterval, NqQuantileMethod, NqFillNullStrategy, NqRoundMode, NqQuoteStyle, NqRankMethod, NqErrorKind, NqStrOp, NqTimeUnit, NqClosedWindow, NqDtOp, NqCatOp, NqParquetCompression and NqIpcCompression SHALL keep the same order as in Rust. NqDtype SHALL also keep the order of DataTypeKind, and the option enums the order of their Nim API enums. Data types SHALL cross the ABI as an NqDtypeSpec struct (code, time unit, time zone, categories) with the same field order on both sides.
- WHEN a function is added or changed in
rust/src/lib.rs - THEN
src/nanuq/ffi.nimis updated in the same change
Linking the static library
Importing nanuq SHALL link libnanuq_ffi.a from the first of these sources that has it: the directory given with -d:nanuqLibDir, the local cargo output of the crate in src/rust/, the prebuilt library (see binary-distribution), and finally a cargo build of src/rust/ run at compile time. -d:nanuqLib=auto (the default) allows all sources. -d:nanuqLib=prebuilt (or -d:nanuqNoCargo) never runs cargo. -d:nanuqLib=source never downloads. The crate SHALL ship inside the installed package, so the cargo fallback also works after nimble install.
- WHEN no local library exists, no prebuilt library is available, and the policy is
autoorsource- THEN compilation runs
cargo build --releaseforsrc/rust/and links the result
- WHEN no local or prebuilt library is available and the policy is
prebuilt - THEN compilation fails with an error naming the expected library path and how to
- get one
- WHEN a user runs
nimble install nanuqon a platform without a prebuilt library - and has cargo
- THEN compiling a program that imports
nanuqbuilds the library from the - installed package's sources and links it
Columns cross in bulk
Reading a whole column into Nim SHALL take a constant number of FFI calls, independent of the number of rows, and SHALL transfer a validity mask alongside the values so nulls are not lost or replaced by placeholder values.
- WHEN a 1,000,000-row float column is read into a Nim seq
- THEN at most two FFI calls are made for that column
- WHEN a column with nulls crosses the boundary
- THEN Nim receives, for every row, whether the value is valid
Library version check
The library SHALL report its version through the C ABI. At startup, Nanuq SHALL compare it with the lib version it was compiled for and stop with an error naming both versions if they differ.
- WHEN
-d:nanuqLibDirpoints at a library built from an older crate version - THEN the program stops at startup with an error naming both versions
Formatted cells
The bridge SHALL return a single cell as text formatted by Polars, as Python Polars' get_fmt does: the value's display form, with strings in quotes and cut to a given number of characters followed by ….
- WHEN a cell holding 5076.016260162602 is formatted
- THEN the text is the same as in Polars' text table,
5076.01626
- WHEN a string of 40 characters is formatted with a limit of 30
- THEN the text is a quote, its first 30 characters and
…
Polars version matches a py-polars release
The nanuq_ffi crate SHALL depend on Polars by the git tag of a py-polars release (py-X.Y.Z), the same version the Nanuq Book and the explainers use as their Python oracle, with the [patch.crates-io] entries of Polars' workspace at that tag; release builds SHALL use that tag's Rust toolchain. Moving to a new py-polars release SHALL move the tag, the patches, the toolchain and the Python oracle together.
- WHEN a book chapter runs the same query in Nanuq and in the pinned py-polars
- THEN the outputs agree, including SQL table functions and seeded
hash/sample
nested-data
Purpose: List, Array and Struct data types, and nested values between Nim and Polars.
Nested data types
DataType SHALL have the kinds List, Array and Struct, built by List(inner), Array(inner, width) (or a shape, Array(Int64, [2, 3])) and Struct(fields) (from {"name": dtype} pairs or a seq of Field). inner, width, shape and fields SHALL read them back, $ SHALL print the constructor call (List(Int64), Array(Int64, [2, 3]), Struct({"x": Float64})) and == SHALL compare the whole type.
let point = Struct({"x": Float64, "y": Float64})
echo List(Int64), " ", Array(Float64, 3), " ", Array(Int64, [2, 3]), " ", point
echo List(point).inner == point, " ", Array(Int64, [2, 3]).shape, " ", point.fields[1].name
List(Int64) Array(Float64, 3) Array(Int64, [2, 3]) Struct({"x": Float64, "y": Float64})
true @[2, 3] y
- WHEN the schema of a frame with a list of strings column is read
- THEN its dtype is
List(String)and$givesList(String)
- WHEN
fieldsis read from the dtype of a struct column built from(x: 1, y: 2.0) - THEN it holds
x: Int64andy: Float64, in order
Nested columns from Nim
series(name, values) SHALL build a List column from seqs, an Array column from Nim arrays, and a Struct column from objects or named tuples, at any depth (seqs of objects, objects with seq fields). Option values SHALL be null rows, and Option elements null values inside a list. The newDataFrame block and toDataFrame(rows) SHALL take the same values; in the block nil SHALL be a null row. lit(seq) SHALL be a list literal.
let df = newDataFrame:
tags: [@["polar", "bear"], @[], nil]
point: [(x: 1, y: 2.0), (x: 3, y: 4.0), (x: 5, y: 6.0)]
rgb: [[255, 0, 0], [0, 255, 0], [0, 0, 255]]
echo df
echo df.select(lit(@[1, 2]).alias("lit"))
shape: (3, 3)
┌───────────────────┬───────────┬───────────────┐
│ tags ┆ point ┆ rgb │
│ --- ┆ --- ┆ --- │
│ list[str] ┆ struct[2] ┆ array[i64, 3] │
╞═══════════════════╪═══════════╪═══════════════╡
│ ["polar", "bear"] ┆ {1,2.0} ┆ [255, 0, 0] │
│ [] ┆ {3,4.0} ┆ [0, 255, 0] │
│ null ┆ {5,6.0} ┆ [0, 0, 255] │
└───────────────────┴───────────┴───────────────┘
shape: (1, 1)
┌───────────┐
│ lit │
│ --- │
│ list[i64] │
╞═══════════╡
│ [1, 2] │
└───────────┘
- WHEN
series("a", newSeq[seq[int]](2))is built - THEN its dtype is
List(Int64)and both values are empty lists
- WHEN
series("a", @[@[some(1), none(int)]])is built - THEN the list holds 1 and null
Nested values to Nim
toList(column, T) SHALL read a List column as seq[U], an Array column as array[N, U] or seq[U], and a Struct column as an object or named tuple matching fields by name, on frames and Series, at any depth; Option[T] SHALL read null rows as none. Cell reads df[column, row, T] and rows(T) SHALL take the same types. A null read into a plain type SHALL raise InvalidOperationError, and an object field without a struct field ColumnNotFoundError.
type Point = object
x: int
y: float
let df = newDataFrame:
tags: [@["polar", "bear"], @[]]
point: [Point(x: 1, y: 2.0), Point(x: 3, y: 4.0)]
echo df.toList("tags", seq[string])
echo df.toList("point", Point)
echo df["point", 1, tuple[x: int]]
for r in df.rows(tuple[tags: seq[string], point: Point]):
echo r.tags.len, " ", r.point.y
@[@["polar", "bear"], @[]]
@[(x: 1, y: 2.0), (x: 3, y: 4.0)]
(x: 3)
2 2.0
0 4.0
- WHEN a seq of objects with seq and object fields is turned into a frame and read back with
rows - THEN the result equals the original seq
- WHEN a list column with a null row is read as
seq[int]rows - THEN
InvalidOperationErroris raised; read asOption[seq[int]]it givesnone
Casting to nested types
cast(dtype) and castTo SHALL accept nested data types, and cast(T) nested Nim types.
let df = newDataFrame(series("a", @[@[1, 2], @[3]]))
echo df.select(col("a").cast(List(Float64)), col("a").cast(seq[string]).alias("s"))
shape: (2, 2)
┌────────────┬────────────┐
│ a ┆ s │
│ --- ┆ --- │
│ list[f64] ┆ list[str] │
╞════════════╪════════════╡
│ [1.0, 2.0] ┆ ["1", "2"] │
│ [3.0] ┆ ["3"] │
└────────────┴────────────┘
- WHEN a list column whose lists all have 2 values is cast to
Array(Int64, 2) - THEN the result is an array column
parquet-ipc
Purpose: Reading and writing Parquet and Arrow IPC (Feather v2) files, lazily or eagerly, from paths or Nim streams.
Reading Parquet
The API SHALL provide scanParquet(path, ...), a lazy scan of a file or a glob, and readParquet(path, ...), which is scanParquet(...).collect. Both SHALL take nRows, columns, rowIndexName with rowIndexOffset = 0, and lowMemory = false. Every dtype Nanuq models SHALL round-trip through Parquet unchanged.
let path = getTempDir() / "riders.parquet"
let df = newDataFrame:
rider: ["Seixas", "Pogačar", "Evenepoel"]
born: [date(2006, 9, 24), date(1998, 9, 21), date(2000, 1, 25)]
wins: [3, 22, nil]
df.writeParquet(path)
echo readParquet(path, columns = ["rider", "born"], nRows = 2, rowIndexName = "nr")
shape: (2, 3)
┌─────┬─────────┬────────────┐
│ nr ┆ rider ┆ born │
│ --- ┆ --- ┆ --- │
│ u32 ┆ str ┆ date │
╞═════╪═════════╪════════════╡
│ 0 ┆ Seixas ┆ 2006-09-24 │
│ 1 ┆ Pogačar ┆ 1998-09-21 │
└─────┴─────────┴────────────┘
- WHEN a DataFrame with string, date and nullable integer columns is written and read back
- THEN the result equals the original, dtypes included
- WHEN bytes that are not Parquet are read
- THEN
PolarsErroris raised
Writing Parquet
writeParquet(df, path, compression = ParquetCompression.Zstd, compressionLevel = none(int), statistics = true, rowGroupSize = none(int)) SHALL write a Parquet file. compressionLevel SHALL apply to Gzip, Brotli and Zstd; with another codec it SHALL raise ValueError, and an out-of-range level SHALL raise PolarsError.
import std/sequtils
let path = getTempDir() / "sizes.parquet"
let df = newDataFrame(series("n", toSeq(1..1000)))
for c in [ParquetCompression.Uncompressed, ParquetCompression.Zstd]:
df.writeParquet(path, compression = c)
echo c, " ", getFileSize(path) < 5000
Uncompressed false
Zstd true
- WHEN a DataFrame is written with each
ParquetCompressionvalue - THEN each file reads back with the same rows
- WHEN
writeParquet(path, compression = ParquetCompression.Snappy, compressionLevel = 3)is called - THEN
ValueErroris raised
- WHEN the target directory does not exist
- THEN
IOErroris raised
Arrow IPC
The API SHALL provide scanIpc and readIpc with the read options of Parquet, and writeIpc(df, path, compression = IpcCompression.Uncompressed) with Lz4 and Zstd.
let path = getTempDir() / "riders.arrow"
let df = newDataFrame:
rider: ["Seixas", "Pogačar"]
start: [timeOfDay(13, 10), timeOfDay(13, 12)]
df.writeIpc(path, compression = IpcCompression.Lz4)
echo readIpc(path).schema
{"rider": String, "start": TimeOfDay}
- WHEN a DataFrame is written with each
IpcCompressionand read back - THEN the result equals the original
Reading from streams
readParquet and readIpc SHALL also take a Nim Stream instead of a path, read all of it when called, and take the same options.
import std/streams
let path = getTempDir() / "one.parquet"
newDataFrame(series("a", [1, 2])).writeParquet(path)
echo readParquet(newStringStream(readFile(path))).shape
(2, 1)
- WHEN the bytes of a Parquet file are read with
readParquet(newStringStream(bytes)) - THEN the result equals reading the file
Hive partitioning switch
scanParquet and readParquet SHALL take hivePartitioning: true reads key=value directories as columns, false does not, none(bool) (default) decides by the path.
let base = getTempDir() / "nanuq-hive"
let df = newDataFrame(series("year", @[2024, 2025]), series("n", @[1, 2]))
df.lazy.sinkParquet(PartitionBy(basePath: base, key: @["year"], includeKey: false), mkdir = true)
echo scanParquet(base / "**/*.parquet", hivePartitioning = false).collect.columns
@["n"]
- WHEN the same files are scanned with
hivePartitioning = true - THEN the frame has a
yearcolumn
Arrow IPC streams
writeIpcStream(path, compression) SHALL write the Arrow IPC stream format, and readIpcStream SHALL read it from a path or a stream.
let path = getTempDir() / "bears.arrows"
newDataFrame(series("kg", @[410, 380])).writeIpcStream(path)
echo readIpcStream(path).toList("kg", int)
@[410, 380]
- WHEN a frame is written with
IpcCompression.Zstdand read back - THEN the frames are equal
plan-serialization
Purpose: Saving and loading query plans and expressions (binary or JSON), and inspecting expressions with the meta namespace.
Serializing query plans
lf.serialize(format = SerializationFormat.Binary) SHALL return the LazyFrame's plan as bytes (in a string), Json as JSON text, and lf.serialize(path, format) SHALL write it to a file. deserialize(LazyFrame, data, format) and deserializeFile(LazyFrame, path, format) SHALL rebuild a LazyFrame that collects to the same result. In-memory frames in the plan SHALL travel with it.
let lf = newDataFrame(series("kg", @[410, 380, 455])).lazy.filter(col("kg") > 400)
let bytes = lf.serialize
echo deserialize(LazyFrame, bytes).collect
echo lf.serialize(SerializationFormat.Json).len > 0
shape: (2, 1)
┌─────┐
│ kg │
│ --- │
│ i64 │
╞═════╡
│ 410 │
│ 455 │
└─────┘
true
- WHEN
deserialize(LazyFrame, "garbage")is called - THEN
PolarsErroris raised
- WHEN a plan with
mapElementsis serialized - THEN
PolarsErroris raised
Serializing expressions
e.meta.serialize(format) SHALL return an expression as bytes or JSON, and deserialize(Expr, data, format) SHALL rebuild it.
let e = (col("kg") * 2).alias("double")
let back = deserialize(Expr, e.meta.serialize)
echo back.meta.eq(e)
echo newDataFrame(series("kg", @[1, 2])).select(back)
true
shape: (2, 1)
┌────────┐
│ double │
│ --- │
│ i64 │
╞════════╡
│ 2 │
│ 4 │
└────────┘
- WHEN an expression is serialized with
Jsonand deserialized withJson - THEN
meta.eqwith the original is true
Expression metadata
The meta namespace SHALL also provide eq(other) and ne(other) (same expression tree), pop (the inputs of the outermost node), isRegexProjection, isColumnSelection(allowAliasing = false), isLiteral(allowAliasing) and treeFormat (the tree as text).
let e = (col("a") + col("b")).alias("c")
echo e.meta.undoAliases.meta.outputName
echo e.meta.pop.len
echo col("^x.*$").meta.isRegexProjection, " ", col("a").alias("b").meta.isColumnSelection(allowAliasing = true)
echo (col("a") + 1).meta.treeFormat
a
1
true true
0 1
┌─────────────────────────────────
│
│ ╭───────────╮
0 │ │ binary: + │
│ ╰─────┬┬────╯
│ ││
│ │╰──────────────╮
│ │ │
│ ╭────────┴────────╮ ╭───┴────╮
1 │ │ lit(dyn int: 1) │ │ col(a) │
│ ╰─────────────────╯ ╰────────╯
- WHEN
col("a").meta.eq(col("b"))is called - THEN it is false
reshaping
Purpose: Changing the shape of a frame: long to wide (pivot), wide to long (unpivot), rows to columns (transpose), splitting by key (partitionBy) and dummy columns.
Pivot
df.pivot(on, index, values, aggregateFunction = PivotAgg.Item, maintainOrder = true, sortColumns = false, separator = "_") SHALL turn each distinct value of the on columns into a column (in order of appearance, or sorted), with one row per distinct index value and cells from values combined by aggregateFunction, a PivotAgg or an expression on element(). When index or values is left out it SHALL mean every other column. lf.pivot(on, onColumns, ...) SHALL do the same lazily with the new columns listed in the DataFrame onColumns.
let df = newDataFrame:
year: [2023, 2023, 2024, 2024]
season: ["DJF", "JJA", "DJF", "JJA"]
oni: [-0.7, 1.1, 1.8, 0.0]
echo df.pivot("season", index = "year", values = "oni")
shape: (2, 3)
┌──────┬──────┬─────┐
│ year ┆ DJF ┆ JJA │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 │
╞══════╪══════╪═════╡
│ 2023 ┆ -0.7 ┆ 1.1 │
│ 2024 ┆ 1.8 ┆ 0.0 │
└──────┴──────┴─────┘
- WHEN two rows share an index and an
onvalue andaggregateFunction = Sum - THEN their cell holds the sum of both values
- WHEN two rows share an index and an
onvalue and no aggregation is given - THEN
pivotraises aPolarsError
Unpivot
unpivot(on, index, variableName = "variable", valueName = "value") on a DataFrame or LazyFrame SHALL turn the on columns (by default every column not in index) into rows, one per index value and on column, holding the column's name and value.
let df = newDataFrame:
year: [2023, 2024]
DJF: [-0.7, 1.8]
JJA: [1.1, 0.0]
echo df.unpivot(index = "year", variableName = "season", valueName = "oni")
shape: (4, 3)
┌──────┬────────┬──────┐
│ year ┆ season ┆ oni │
│ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ f64 │
╞══════╪════════╪══════╡
│ 2023 ┆ DJF ┆ -0.7 │
│ 2024 ┆ DJF ┆ 1.8 │
│ 2023 ┆ JJA ┆ 1.1 │
│ 2024 ┆ JJA ┆ 0.0 │
└──────┴────────┴──────┘
- WHEN a long frame is pivoted and the result unpivoted on the new columns
- THEN the rows are the original rows
Transpose
df.transpose(includeHeader = false, headerName = "column", columnNames) SHALL turn rows into columns, naming them columnNames or column_0, column_1, ..., and with includeHeader SHALL put the old column names in a first column headerName.
let df = newDataFrame:
lima: [22.1, 24.3]
quito: [14.0, 14.2]
echo df.transpose(includeHeader = true, headerName = "station", columnNames = ["jan", "feb"])
shape: (2, 3)
┌─────────┬──────┬──────┐
│ station ┆ jan ┆ feb │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞═════════╪══════╪══════╡
│ lima ┆ 22.1 ┆ 24.3 │
│ quito ┆ 14.0 ┆ 14.2 │
└─────────┴──────┴──────┘
- WHEN a frame with two rows is transposed without names
- THEN its columns are column_0 and column_1
Partition
df.partitionBy(by, maintainOrder = true, includeKey = true) SHALL return one DataFrame per distinct value of the by columns, in order of appearance with maintainOrder, and without the by columns when includeKey is false.
let df = newDataFrame:
phase: ["El Niño", "La Niña", "El Niño"]
year: [2015, 2020, 2023]
for part in df.partitionBy("phase", includeKey = false):
echo part.toList("year", int)
@[2015, 2023]
@[2020]
- WHEN
partitionBy(["a", "b"])runs on rows with three distinct (a, b) pairs - THEN the result has three frames
Dummy columns
df.toDummies(columns, separator = "_", dropFirst = false, dropNulls = false) SHALL replace each listed column (all by default) by one 0/1 column per distinct value, named column, separator and value.
let df = newDataFrame:
phase: ["warm", "cold", "warm"]
echo df.toDummies()
shape: (3, 2)
┌────────────┬────────────┐
│ phase_cold ┆ phase_warm │
│ --- ┆ --- │
│ u8 ┆ u8 │
╞════════════╪════════════╡
│ 0 ┆ 1 │
│ 1 ┆ 0 │
│ 0 ┆ 1 │
└────────────┴────────────┘
- WHEN
toDummies(dropFirst = true)runs on a column with values a and b - THEN only one dummy column remains
rolling-windows
Purpose: Statistics over moving windows: a fixed number of rows, or a time span of a sorted column, and exponentially weighted statistics.
Fixed rolling windows
rollingSum, rollingMean, rollingMin, rollingMax, rollingMedian, rollingStd, rollingVar and rollingQuantile SHALL compute their statistic over the last windowSize rows, or over a window centred on each row with center = true. A row SHALL get null until minSamples non-null values are in its window (by default windowSize), and weights, when given, SHALL multiply the values of each window.
let df = newDataFrame:
season: ["NDJ", "DJF", "JFM", "FMA", "MAM"]
anomaly: [1.9, 2.1, 1.6, 1.0, 0.4]
echo df.withColumns(col.anomaly.rollingMean(3).round(2).alias("mean3"),
col.anomaly.rollingMean(3, center = true).round(2).alias("centred"),
col.anomaly.rollingMax(2, minSamples = 1).alias("max2"))
shape: (5, 5)
┌────────┬─────────┬───────┬─────────┬──────┐
│ season ┆ anomaly ┆ mean3 ┆ centred ┆ max2 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞════════╪═════════╪═══════╪═════════╪══════╡
│ NDJ ┆ 1.9 ┆ null ┆ null ┆ 1.9 │
│ DJF ┆ 2.1 ┆ null ┆ 1.87 ┆ 2.1 │
│ JFM ┆ 1.6 ┆ 1.87 ┆ 1.57 ┆ 2.1 │
│ FMA ┆ 1.0 ┆ 1.57 ┆ 1.0 ┆ 1.6 │
│ MAM ┆ 0.4 ┆ 1.0 ┆ null ┆ 1.0 │
└────────┴─────────┴───────┴─────────┴──────┘
- WHEN
rollingSum(3)runs on 1, 2, 3, 4 - THEN the result is null, null, 6, 9
- WHEN
rollingSum(2, weights = [0.5, 1.0])runs on 2.0, 4.0 - THEN the second value is 5.0
- WHEN
rollingMean(0)is built - THEN
ValueErroris raised
Time rolling windows
The same functions with a By suffix SHALL take a sorted column by (temporal or integer) and a window size as a std/times interval or Polars duration string; the window of each row SHALL span windowSize back from its by value, with ends included as closed (ClosedWindow, default Right) says, and rows SHALL need minSamples values (default 1).
let df = newDataFrame:
day: [date(2026, 7, 1), date(2026, 7, 2), date(2026, 7, 5), date(2026, 7, 6)]
rain: [4, 0, 10, 2]
echo df.withColumns(col.rain.rollingSumBy("day", 3.days).alias("last_3_days"))
shape: (4, 3)
┌────────────┬──────┬─────────────┐
│ day ┆ rain ┆ last_3_days │
│ --- ┆ --- ┆ --- │
│ date ┆ i64 ┆ i64 │
╞════════════╪══════╪═════════════╡
│ 2026-07-01 ┆ 4 ┆ 4 │
│ 2026-07-02 ┆ 0 ┆ 4 │
│ 2026-07-05 ┆ 10 ┆ 10 │
│ 2026-07-06 ┆ 2 ┆ 12 │
└────────────┴──────┴─────────────┘
- WHEN
rollingSumBy("day", 3.days)runs on July 1, 2, 5, 6 with 4, 0, 10, 2 - THEN the result is 4, 4, 10, 12
Exponentially weighted functions
ewmMean, ewmStd and ewmVar SHALL compute exponentially weighted statistics with the decay given by exactly one of com, span, halfLife or alpha, converted to alpha as Python Polars does, and SHALL take adjust, minSamples and ignoreNulls (and bias for std and var). Giving none or more than one decay parameter SHALL raise ValueError.
let df = newDataFrame:
temp: [14.0, 15.0, 13.0, 16.0]
echo df.withColumns(col.temp.ewmMean(alpha = 0.5).round(3).alias("ewm"),
col.temp.ewmMean(span = 3, adjust = false).round(3).alias("span3"))
shape: (4, 3)
┌──────┬────────┬────────┐
│ temp ┆ ewm ┆ span3 │
│ --- ┆ --- ┆ --- │
│ f64 ┆ f64 ┆ f64 │
╞══════╪════════╪════════╡
│ 14.0 ┆ 14.0 ┆ 14.0 │
│ 15.0 ┆ 14.667 ┆ 14.5 │
│ 13.0 ┆ 13.714 ┆ 13.75 │
│ 16.0 ┆ 14.933 ┆ 14.875 │
└──────┴────────┴────────┘
- WHEN
ewmMean(span = 3)andewmMean(alpha = 0.5)run on the same column - THEN the results are equal
- WHEN
ewmMean(com = 1, alpha = 0.5)is built - THEN
ValueErroris raised
row-objects
Purpose: Reading the rows of a frame as typed Nim objects or named tuples, and building a frame from a seq of objects.
Rows as objects
df.rows(T) SHALL return the rows as a seq[T] and df.iterRows(T) SHALL iterate them, for T an object or named tuple whose fields are named after columns, and df.row(i, T) SHALL return row i (negative from the end). Fields SHALL be int, float, bool, string, temporal values, Nim enums, or Option of these; a null read into a plain field SHALL raise InvalidOperationError, and a field without a column ColumnNotFoundError.
type Reading = object
station: string
rain: float
let df = newDataFrame:
station: ["Lima", "Piura", "Tumbes"]
rain: [1.5, 80.0, 95.0]
year: [1998, 1998, 1998]
for r in df.iterRows(Reading):
echo r.station, ": ", r.rain
echo df.row(-1, tuple[station: string, year: int])
Lima: 1.5
Piura: 80.0
Tumbes: 95.0
(station: "Tumbes", year: 1998)
- WHEN
rowsis called with a type that has a fieldwindand the frame has no columnwind - THEN
ColumnNotFoundErroris raised
Objects to a frame
toDataFrame(rows) SHALL build a frame from a seq or array of objects or named tuples, with one column per field in field order; Option fields SHALL give columns with nulls.
type Event = object
year: int
peak: Option[float]
let events = @[Event(year: 1997, peak: some(2.4)), Event(year: 2014, peak: none(float))]
echo events.toDataFrame
shape: (2, 2)
┌──────┬──────┐
│ year ┆ peak │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞══════╪══════╡
│ 1997 ┆ 2.4 │
│ 2014 ┆ null │
└──────┴──────┘
- WHEN a seq of objects is turned into a frame and read back with
rows - THEN the result equals the original seq
series
Purpose: Single columns as Series: getting them from frames, reading them, operating on them through the expression methods of the same name, and putting them back into frames.
Getting a Series
df["name"] and df.getColumn("name") SHALL return the column as a Series, and df.toSeries(index = 0) the column at a position (negative from the end); a missing column SHALL raise ColumnNotFoundError. A Series SHALL have name, len, dtype, nullCount and $, which shows Polars' Series display.
let df = newDataFrame:
year: [1997, 2015, 2023]
oni: [2.4, 2.6, 2.0]
let s = df["oni"]
echo s
echo s.name, " ", s.len, " ", s.dtype
shape: (3,)
Series: 'oni' [f64]
[
2.4
2.6
2.0
]
oni 3 Float64
- WHEN
df["nope"]runs on a frame without that column - THEN
ColumnNotFoundErroris raised
Reading a Series
s.toList(T) and s.toList(Option[T]) SHALL return the values, s[i, T] one value, and s.item(T) the only value of a one-value Series (raising InvalidOperationError otherwise). toFrame SHALL return a one-column frame, and alias/rename and cast SHALL return a renamed or converted Series.
let s = series("oni", [2.4, 2.6, 2.0])
echo s.toList(float), " ", s[1, float]
echo s.toFrame.columns
@[2.4, 2.6, 2.0] 2.6
@["oni"]
- WHEN
item(float)is called on a Series of three values - THEN
InvalidOperationErroris raised
Series operations
Series SHALL support the arithmetic, comparison and boolean operators with literals and other Series of the same length, filter(mask), and the expression methods that take no other column (aggregations, math, cumulative, rolling, ranking, distinct values, recoding, binning), each SHALL give the same values as the expression of the same name on a one-column frame. Aggregations SHALL return a Series of one value.
let s = series("oni", [0.5, -1.0, 2.0, 1.2])
echo s.max.item(float)
echo ((s - s.mean.item(float)) / s.std.item(float)).round(2).toList(float)
echo s.filter(s > 0.5).toList(float)
echo s.rollingMean(2).toList(Option[float])
2.0
@[-0.14, -1.31, 1.04, 0.41]
@[2.0, 1.2]
@[none(float), some(-0.25), some(0.5), some(1.6)]
- WHEN
a + bruns on Series a = 1, 2 and b = 10, 20 - THEN the result is 11, 22 named like
a
Series in frames
df.withColumns(series...) SHALL add or replace columns with Series of the frame's height, and lit(series) SHALL use a Series as a column in an expression.
let df = newDataFrame:
year: [1997, 2015, 2023]
let peak = series("peak", [2.4, 2.6, 2.0])
echo df.withColumns(peak, (peak * 10).alias("tenths"))
shape: (3, 3)
┌──────┬──────┬────────┐
│ year ┆ peak ┆ tenths │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 │
╞══════╪══════╪════════╡
│ 1997 ┆ 2.4 ┆ 24.0 │
│ 2015 ┆ 2.6 ┆ 26.0 │
│ 2023 ┆ 2.0 ┆ 20.0 │
└──────┴──────┴────────┘
- WHEN
select(col.year + lit(series("d", [1, 1, 1])))runs - THEN each year grows by one
Series namespaces
A Series SHALL have the namespaces list, arr, struct, str, dt and cat, each offering every function of the Expr namespace of the same name: s.ns.f(args) SHALL return the Series s.eval(col(s.name).ns.f(args)). The result keeps the name the expression gives (so s.struct.field("x") is named x).
let df = newDataFrame:
p: [(x: 1, y: 2.0), (x: 3, y: 4.0)]
l: [@[1, 2], @[3]]
echo df["p"].struct.field("x")
echo df["l"].list.len
shape: (2,)
Series: 'x' [i64]
[
1
3
]
shape: (2,)
Series: 'l' [u32]
[
2
1
]
- WHEN
s.str.toUppercaseruns on a String Series holding "ab" and "c" - THEN the result holds "AB" and "C"
Series as HTML
toHtml(s: Series, maxRows = 10) SHALL return the HTML that Python Polars shows for a Series in notebooks: the table of its one column, with the shape written (n,).
let s = series("kg", [410, 380])
echo s.toHtml
<div><style>
.dataframe > thead > tr,
.dataframe > tbody > tr {
text-align: right;
white-space: pre-wrap;
}
</style>
<small>shape: (2,)</small><table border="1" class="dataframe"><thead><tr><th>kg</th></tr><tr><td>i64</td></tr></thead><tbody><tr><td>410</td></tr><tr><td>380</td></tr></tbody></table></div>
- WHEN a Series of 3 values is turned into HTML
- THEN the HTML shows
shape: (3,)
Columns from sized numbers
series, newDataFrame, lists and arrays SHALL accept int8, int16, int32, int64, uint8, uint16, uint32, uint64 and float32 values (and Option of them), giving the Polars type of the same size, and toList SHALL read columns back as those types.
let df = newDataFrame:
rgb: [[255'u8, 0, 0], [0'u8, 128, 255]]
temp: [-1.5'f32, 2.0]
echo df
echo df.toList("temp", float32)
shape: (2, 2)
┌───────────────┬──────┐
│ rgb ┆ temp │
│ --- ┆ --- │
│ array[u8, 3] ┆ f32 │
╞═══════════════╪══════╡
│ [255, 0, 0] ┆ -1.5 │
│ [0, 128, 255] ┆ 2.0 │
└───────────────┴──────┘
@[-1.5, 2.0]
- WHEN
series("a", [1'i32, 2])is built - THEN its data type is Int32 and
toList(int32)gives@[1'i32, 2]
Binary functions on a Series
s.bin SHALL give the bin namespace on a Series, as on an expression.
let s = newDataFrame(series("b", @["ab", "c"])).select(col("b").cast(Binary)).getColumn("b")
echo s.bin.size
shape: (2,)
Series: 'b' [u32]
[
2
1
]
- WHEN
s.bin.sizeruns - THEN it equals
s.eval(col(s.name).bin.size)
spec-examples
Purpose: Runnable Nim examples in the OpenSpec specs: where they go, how they are checked against the code, and how specview shows them.
API requirements have examples
Every requirement in openspec/specs/ that describes Nim API SHALL include an example: a
allowed use; failures stay in scenarios. Requirements about process (CI, releases, the dev log, the C ABI) need none.
let df = newDataFrame(series("a", [1, 2, 3]))
echo df.select(col("a").isIn([1, 3]))
shape: (3, 1)
┌───────┐
│ a │
│ --- │
│ bool │
╞═══════╡
│ true │
│ false │
│ true │
└───────┘
- WHEN a change adds or modifies a requirement that describes Nim API
- THEN its delta includes the example and the expected output
- WHEN a requirement describes CI or the release process
- THEN it has no example
Examples are run
Every nim block in openspec/specs/ SHALL be a unittest test of the test suite (tests/test_specs*.nim, named <capability>:<line>), with nanuq, nanuq/datasets and std/[options, os, strutils]` imported, that fails when the example does not compile, fails at run time, or prints something other than its
their own. `nimble specexamples` SHALL check the same examples, and with `--update`
write the actual output into the text blocks instead. Change deltas SHALL NOT be run.
nim r tests/test_specs.nim "spec expressions::*" # check one spec nimble specexamples # check every spec nim r tools/specexamples.nim --update expressions # refresh one spec's outputs
spec-review
Purpose: What the specview review page (tools/specview.nim) shows.
Full specs in specview
specview SHALL render every spec in openspec/specs/ in full, with its purpose, requirements, examples and scenarios, and SHALL mark the specs that an open change modifies or that changed since --base.
- WHEN a reviewer opens the Specs section and expands
temporal - THEN every requirement of
openspec/specs/temporal/spec.mdis shown with its example and scenarios
Archived changes are hidden by default
specview SHALL hide archived changes until the reader ticks "Show archived changes", except archived changes that changed since --base. A link to a hidden change SHALL reveal it.
- WHEN specview runs without
--baseon a repository whose changes are all archived - THEN no change is shown until the checkbox is ticked
- WHEN specview runs with
--base:origin/mainon a branch that archived three changes - THEN those three changes are shown and the other archived ones are hidden
sql
Purpose: Running SQL queries on frames: contexts, frames by variable name, and SQL on a frame.
SQL contexts
newSQLContext() SHALL make an empty context and newSQLContext({"name": frame}) one with frames registered; register(name, frame) SHALL add a LazyFrame or DataFrame, unregister(name) remove it and tables list the names in sorted order; execute(query) SHALL run a SQL query on the registered frames and give a LazyFrame, or a DataFrame with eager = true.
let bears = newDataFrame:
bear: ["Ada", "Bo", "Cy"]
kg: [410, 380, 500]
let ctx = newSQLContext({"bears": bears.lazy})
echo ctx.tables
echo ctx.execute("SELECT bear, kg FROM bears WHERE kg > 400 ORDER BY kg DESC", eager = true)
@["bears"]
shape: (2, 2)
┌──────┬─────┐
│ bear ┆ kg │
│ --- ┆ --- │
│ str ┆ i64 │
╞══════╪═════╡
│ Cy ┆ 500 │
│ Ada ┆ 410 │
└──────┴─────┘
- WHEN a query reads a table that is not registered
- THEN
SqlErroris raised
Frames by variable name
sqlContext(a, b, ...) SHALL make a context with each frame registered under the name of the variable passed.
let bears = newDataFrame:
bear: ["Ada", "Bo"]
den: [1, 2]
let dens = newDataFrame:
den: [1, 2]
site: ["Kong Karls Land", "Hopen"]
let ctx = sqlContext(bears, dens)
echo ctx.execute("SELECT bear, site FROM bears JOIN dens USING (den) ORDER BY bear").collect
shape: (2, 2)
┌──────┬─────────────────┐
│ bear ┆ site │
│ --- ┆ --- │
│ str ┆ str │
╞══════╪═════════════════╡
│ Ada ┆ Kong Karls Land │
│ Bo ┆ Hopen │
└──────┴─────────────────┘
- WHEN
sqlContext(bears.lazy)is compiled - THEN compilation fails with a message asking for a variable
SQL on a frame
df.sql(query) and lf.sql(query) SHALL run a query on the frame, which the query calls self (or tableName), and sql(query, {"name": frame}) SHALL run a query on the given frames.
let df = newDataFrame:
island: ["Biscoe", "Dream", "Biscoe"]
kg: [4.5, 3.7, 5.1]
echo df.sql("SELECT island, AVG(kg) AS kg FROM self GROUP BY island ORDER BY island")
shape: (2, 2)
┌────────┬─────┐
│ island ┆ kg │
│ --- ┆ --- │
│ str ┆ f64 │
╞════════╪═════╡
│ Biscoe ┆ 4.8 │
│ Dream ┆ 3.7 │
└────────┴─────┘
- WHEN
df.sql("SELECT * FROM penguins", tableName = "penguins")is run - THEN the result is the frame
streaming
Purpose: Running lazy queries on Polars' streaming engine and writing results straight to files (sinks), whole or partitioned by key, without holding them in memory.
Choosing the engine
collect(lf, engine) SHALL run the query with the given Engine: Auto (Polars picks, today the in-memory engine), InMemory or Streaming, which processes the data in batches. Every engine SHALL give the same rows; collectAll(lfs, engine) SHALL take the same choice.
let lf = newDataFrame(series("kg", @[410, 380, 455])).lazy
echo lf.filter(col("kg") > 400).collect(engine = Engine.Streaming)
shape: (2, 1)
┌─────┐
│ kg │
│ --- │
│ i64 │
╞═════╡
│ 410 │
│ 455 │
└─────┘
- WHEN a group-by query is collected with
Engine.InMemoryand withEngine.Streaming - THEN both frames are equal after sorting
Sinks
sinkParquet, sinkIpc, sinkCsv and sinkNdjson SHALL run a LazyFrame with the streaming engine and write the result to a file, with the options of writeParquet, writeIpc, writeCsv and writeNdjson, plus maintainOrder = true and mkdir = false (create missing directories). With lazy = true they SHALL return the sink as a LazyFrame, which writes the file when collected; collectAll SHALL run several such sinks together.
let dir = getTempDir() / "nanuq-sinks"
let lf = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410, 380])).lazy
lf.sinkCsv(dir / "bears.csv", mkdir = true)
echo readFile(dir / "bears.csv")
let sinks = [lf.sinkParquet(dir / "bears.parquet", lazy = true),
lf.filter(col("kg") > 400).sinkNdjson(dir / "big.ndjson", lazy = true)]
discard collectAll(sinks)
echo readParquet(dir / "bears.parquet").height, " ", readFile(dir / "big.ndjson")
bear,kg
Ada,410
Bo,380
2 {"bear":"Ada","kg":410}
- WHEN a sink targets a directory that does not exist and
mkdiris false - THEN
IOErroris raised and no file is written
Partitioned sinks
A sink SHALL accept a PartitionBy(basePath, key, includeKey = true, maxRowsPerFile) target instead of a path: with key it SHALL write one Hive-style directory per key value (basePath/key=value/...), without it files of at most maxRowsPerFile rows.
let base = getTempDir() / "nanuq-by-year"
let df = newDataFrame(series("year", @[2024, 2024, 2025]), series("n", @[1, 2, 3]))
df.lazy.sinkParquet(PartitionBy(basePath: base, key: @["year"]), mkdir = true)
echo scanParquet(base / "**/*.parquet").sort("n").collect
shape: (3, 2)
┌──────┬─────┐
│ year ┆ n │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞══════╪═════╡
│ 2024 ┆ 1 │
│ 2024 ┆ 2 │
│ 2025 ┆ 3 │
└──────┴─────┘
- WHEN 10 rows are sunk with
PartitionBy(basePath: dir, maxRowsPerFile: 4) - THEN reading every file in
dirgives the 10 rows back
strings
Purpose: String expressions: the str namespace, concatStr and format.
The str namespace
e.str SHALL give access to string functions that return expressions: lenChars, lenBytes, toUppercase, toLowercase and reverse. Nulls SHALL stay null in every string function, unless stated otherwise.
let df = newDataFrame:
rider: ["Pogačar", "Seixas", nil]
echo df.select(col.rider, col.rider.str.toUppercase.alias("upper"),
col.rider.str.lenChars.alias("chars"), col.rider.str.lenBytes.alias("bytes"))
shape: (3, 4)
┌─────────┬─────────┬───────┬───────┐
│ rider ┆ upper ┆ chars ┆ bytes │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ u32 ┆ u32 │
╞═════════╪═════════╪═══════╪═══════╡
│ Pogačar ┆ POGAČAR ┆ 7 ┆ 8 │
│ Seixas ┆ SEIXAS ┆ 6 ┆ 6 │
│ null ┆ null ┆ null ┆ null │
└─────────┴─────────┴───────┴───────┘
- WHEN
str.lenCharsandstr.lenBytesrun over "Pogačar" - THEN the results are 7 and 8
- WHEN
str.toUppercaseruns over an i64 column - THEN
PolarsErroris raised when the query runs
Matching
The namespace SHALL provide startsWith(prefix), endsWith(suffix), contains(pattern, literal = false, strict = true), find(pattern, literal = false, strict = true), countMatches(pattern, literal = false) and extract(pattern, groupIndex = 1). Patterns SHALL be Rust regular expressions unless literal = true. With strict = false, an invalid regex SHALL give null instead of raising.
let df = newDataFrame:
race: ["Paris–Nice", "Milano-Sanremo", "Tour de France"]
echo df.select(col.race,
col.race.str.contains("–", literal = true).alias("en_dash"),
col.race.str.startsWith("Tour").alias("tour"),
col.race.str.extract(r"^(\w+)", 1).alias("first"),
col.race.str.countMatches("[aeiou]").alias("vowels"))
shape: (3, 5)
┌────────────────┬─────────┬───────┬────────┬────────┐
│ race ┆ en_dash ┆ tour ┆ first ┆ vowels │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ bool ┆ bool ┆ str ┆ u32 │
╞════════════════╪═════════╪═══════╪════════╪════════╡
│ Paris–Nice ┆ true ┆ false ┆ Paris ┆ 4 │
│ Milano-Sanremo ┆ false ┆ false ┆ Milano ┆ 6 │
│ Tour de France ┆ false ┆ true ┆ Tour ┆ 5 │
└────────────────┴─────────┴───────┴────────┴────────┘
- WHEN
str.contains(".")andstr.contains(".", literal = true)run over "abc" - THEN the results are true and false
- WHEN
str.extract(r"(\d+)'")runs over "73h" - THEN the result is null
- WHEN
str.contains("(")runs, and thenstr.contains("(", strict = false) - THEN the first raises
PolarsErrorand the second gives null
Replacing and stripping
The namespace SHALL provide replace(pattern, value, literal = false, n = 1), replaceAll(pattern, value, literal = false), stripChars, stripCharsStart and stripCharsEnd (whitespace without an argument, otherwise the given characters), stripPrefix(prefix) and stripSuffix(suffix). In a regex replacement, $1 SHALL refer to a capture group.
let df = newDataFrame:
race: [" Paris–Nice ", "Tirreno–Adriatico", "Strade Bianche"]
echo df.select(col.race.str.stripChars.str.replaceAll("–", "-", literal = true).alias("clean"),
col.race.str.replace(r"(\w+) (\w+)", "$2 $1").alias("swapped"))
shape: (3, 2)
┌───────────────────┬───────────────────┐
│ clean ┆ swapped │
│ --- ┆ --- │
│ str ┆ str │
╞═══════════════════╪═══════════════════╡
│ Paris-Nice ┆ Paris–Nice │
│ Tirreno-Adriatico ┆ Tirreno–Adriatico │
│ Strade Bianche ┆ Bianche Strade │
└───────────────────┴───────────────────┘
- WHEN
str.replace("a", "o", n = 2)runs over "banana" - THEN the result is "bonona"
- WHEN
str.stripChars("*")runs over "win" - THEN the result is "win"
Slicing and padding
The namespace SHALL provide slice(offset) and slice(offset, length) (a negative offset counts from the end), head(n), tail(n), padStart(length, fillChar = ' '), padEnd(length, fillChar = ' ') and zfill(length), counting characters.
let df = newDataFrame:
bib: ["1", "21", "141"]
nat: ["SLO", "FRA", "DEN"]
echo df.select(col.bib.str.zfill(3).alias("bib"), col.bib.str.padStart(4, '.').alias("dots"),
col.nat.str.head(2).alias("head"), col.nat.str.slice(-2).alias("last2"))
shape: (3, 4)
┌─────┬──────┬──────┬───────┐
│ bib ┆ dots ┆ head ┆ last2 │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str │
╞═════╪══════╪══════╪═══════╡
│ 001 ┆ ...1 ┆ SL ┆ LO │
│ 021 ┆ ..21 ┆ FR ┆ RA │
│ 141 ┆ .141 ┆ DE ┆ EN │
└─────┴──────┴──────┴───────┘
- WHEN
str.slice(1, 2)runs over "Pogačar" - THEN the result is "og"
Joining strings in an aggregation
str.join(delimiter = "", ignoreNulls = true) SHALL aggregate a column into one string, in row order, per group in agg. With ignoreNulls = false, a null SHALL make the result null.
let wins = newDataFrame:
rider: ["Pogačar", "Seixas", "Pogačar"]
race: ["Strade Bianche", "Flèche Wallonne", "Il Lombardia"]
echo wins.groupBy(col.rider).agg(col.race.str.join(", ").alias("races")).sort("rider")
shape: (2, 2)
┌─────────┬──────────────────────────────┐
│ rider ┆ races │
│ --- ┆ --- │
│ str ┆ str │
╞═════════╪══════════════════════════════╡
│ Pogačar ┆ Strade Bianche, Il Lombardia │
│ Seixas ┆ Flèche Wallonne │
└─────────┴──────────────────────────────┘
- WHEN
select(col.race.str.join("|"))runs over "a", null, "b" - THEN the result is one row holding "a|b"
Building strings from columns
concatStr(exprs, separator = "", ignoreNulls = false) SHALL concatenate expressions row by row into a string column, and format(template, args...) SHALL replace each {} in template by the next argument. Non-string arguments SHALL be formatted as Polars casts them to strings. A null argument SHALL make the row null, unless ignoreNulls = true in concatStr. A template whose placeholders don't match the number of arguments SHALL raise ValueError.
let gaps = newDataFrame:
rider: ["Vingegaard", "Pogačar"]
minutes: [4, 0]
seconds: [23, 7]
echo gaps.select(format("{}: {}′ {}″", col.rider, col.minutes, col.seconds).alias("gap"),
concatStr([col.rider, lit("UAE")], separator = " / ").alias("team"))
shape: (2, 2)
┌────────────────────┬──────────────────┐
│ gap ┆ team │
│ --- ┆ --- │
│ str ┆ str │
╞════════════════════╪══════════════════╡
│ Vingegaard: 4′ 23″ ┆ Vingegaard / UAE │
│ Pogačar: 0′ 7″ ┆ Pogačar / UAE │
└────────────────────┴──────────────────┘
- WHEN
format("{} {}", col.a)is called - THEN
ValueErroris raised
- WHEN a module imports
std/strutilsandnanuqand callsformat("{}", col.a)and"$1".format("x") - THEN both compile, the first giving an expression and the second "x"
Title case
str.toTitlecase SHALL upper-case the first letter of each word and lower-case the rest, when the native library is built with the nightly feature, as the release libraries are. With a library built without it, it SHALL raise InvalidOperationError when the expression is built.
- WHEN
str.toTitlecaseruns over "tour de france" with a release library - THEN the result is "Tour De France"
- WHEN
str.toTitlecaseis called with a library built on stable Rust - THEN
InvalidOperationErroris raised
Splitting and extracting into lists and structs
str.split(by) SHALL split each string into a list[str] (keeping by with inclusive = true), str.extractAll(pattern) SHALL give all regex matches as a list, str.splitExact(by, n) and str.splitn(by, n) SHALL give a struct of n + 1 or n fields named field_0, ..., and str.extractGroups(pattern) SHALL give a struct with one field per capture group, named after named groups or numbered from 1.
let df = newDataFrame:
station: ["Lima, Peru", "Piura, Peru", "Darwin"]
echo df.select(col("station").str.split(", ").alias("parts"),
col("station").str.splitExact(", ", 1).alias("exact"),
col("station").str.extractGroups(r"(?<city>\w+)(, (?<country>\w+))?").alias("groups"))
shape: (3, 3)
┌───────────────────┬──────────────────┬───────────────────────────┐
│ parts ┆ exact ┆ groups │
│ --- ┆ --- ┆ --- │
│ list[str] ┆ struct[2] ┆ struct[3] │
╞═══════════════════╪══════════════════╪═══════════════════════════╡
│ ["Lima", "Peru"] ┆ {"Lima","Peru"} ┆ {"Lima",", Peru","Peru"} │
│ ["Piura", "Peru"] ┆ {"Piura","Peru"} ┆ {"Piura",", Peru","Peru"} │
│ ["Darwin"] ┆ {"Darwin",null} ┆ {"Darwin",null,null} │
└───────────────────┴──────────────────┴───────────────────────────┘
- WHEN
splitExact(", ", 1)is evaluated on a string without a comma - THEN the second field is null
Many patterns at once
str.containsAny(patterns), str.replaceMany(patterns, replaceWith) (or a mapping), str.extractMany(patterns) and str.findMany(patterns) SHALL match many literal patterns in one pass, with asciiCaseInsensitive and, for extract and find, overlapping.
let df = newDataFrame:
note: ["sea ice thin", "no ice", "open water"]
echo df.select(col("note").str.containsAny(["ice", "water"]).alias("any"),
col("note").str.replaceMany({"ice": "ICE", "water": "WATER"}).alias("loud"),
col("note").str.extractMany(["ice", "sea", "water"]).alias("found"))
shape: (3, 3)
┌──────┬──────────────┬────────────────┐
│ any ┆ loud ┆ found │
│ --- ┆ --- ┆ --- │
│ bool ┆ str ┆ list[str] │
╞══════╪══════════════╪════════════════╡
│ true ┆ sea ICE thin ┆ ["sea", "ice"] │
│ true ┆ no ICE ┆ ["ice"] │
│ true ┆ open WATER ┆ ["water"] │
└──────┴──────────────┴────────────────┘
- WHEN
replaceMany(["a", "b"], "_")is evaluated on "abc" - THEN the result is "__c"
JSON in strings
str.jsonDecode(dtype) (or jsonDecode(T) with a Nim type) SHALL parse each string as JSON into a value of dtype, and str.jsonPathMatch(path) SHALL give the string at a JSONPath, null when there is none.
let df = newDataFrame:
json: ["""{"bear": "Ada", "kg": 410}""", """{"bear": "Bo", "kg": null}"""]
echo df.select(col("json").str.jsonDecode(tuple[bear: string, kg: Option[int]]).alias("v"),
col("json").str.jsonPathMatch("$.bear").alias("bear"))
shape: (2, 2)
┌─────────────┬──────┐
│ v ┆ bear │
│ --- ┆ --- │
│ struct[2] ┆ str │
╞═════════════╪══════╡
│ {"Ada",410} ┆ Ada │
│ {"Bo",null} ┆ Bo │
└─────────────┴──────┘
- WHEN a string that is not JSON is decoded
- THEN
ComputeErroris raised
Escaping and normalizing
str.escapeRegex SHALL escape regex metacharacters, and str.normalize(form = UnicodeForm.NFC) SHALL give the Unicode normal form (NFC, NFKC, NFD, NFKD).
let df = newDataFrame(series("s", @["a.b*c", "é"]))
echo df.select(col("s").str.escapeRegex.alias("escaped"),
col("s").str.normalize.str.lenChars.alias("chars"))
shape: (2, 2)
┌─────────┬───────┐
│ escaped ┆ chars │
│ --- ┆ --- │
│ str ┆ u32 │
╞═════════╪═══════╡
│ a\.b\*c ┆ 5 │
│ é ┆ 1 │
└─────────┴───────┘
- WHEN "e" followed by a combining acute accent is normalized to NFC
- THEN the result is the one character "é"
struct-functions
Purpose: Struct construction, the struct and arr namespaces, unnest and expression valueCounts.
Building structs
asStruct(exprs) SHALL build a struct column with one field per expression, named after its output name.
let df = newDataFrame:
bear: ["Ada", "Bo"]
kg: [410, 380]
echo df.select(asStruct(col("bear"), col("kg") * 2).alias("s"))
shape: (2, 1)
┌─────────────┐
│ s │
│ --- │
│ struct[2] │
╞═════════════╡
│ {"Ada",820} │
│ {"Bo",760} │
└─────────────┘
- WHEN two expressions with the same output name are put in one struct
- THEN
DuplicateErroris raised
Struct fields
e.struct.field(name) (also e.struct[name]) SHALL give one field as a column, field(names) several, field(index) one by position, and e.struct.unnest all of them; renameFields(names) SHALL rename the fields in order, withFields(exprs) add or replace fields, and jsonEncode give each struct as a JSON string.
let df = newDataFrame:
p: [(x: 1, y: 2.0), (x: 3, y: 4.0)]
echo df.select(col("p").struct.field("x"), col("p").struct["y"].alias("y"),
col("p").struct.jsonEncode.alias("json"))
echo df.select(col("p").struct.renameFields(["a", "b"]).struct.unnest)
shape: (2, 3)
┌─────┬─────┬─────────────────┐
│ x ┆ y ┆ json │
│ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ str │
╞═════╪═════╪═════════════════╡
│ 1 ┆ 2.0 ┆ {"x":1,"y":2.0} │
│ 3 ┆ 4.0 ┆ {"x":3,"y":4.0} │
└─────┴─────┴─────────────────┘
shape: (2, 2)
┌─────┬─────┐
│ a ┆ b │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞═════╪═════╡
│ 1 ┆ 2.0 │
│ 3 ┆ 4.0 │
└─────┴─────┘
- WHEN
struct.field("z")is evaluated on a struct withoutz - THEN
StructFieldNotFoundErroris raised
Unnesting frames
df.unnest(columns) SHALL replace each struct column by its fields (eager and lazy); with separator, the new columns SHALL be named <column><separator><field>.
let df = newDataFrame:
bear: ["Ada", "Bo"]
den: [(lat: 78.2, lon: 15.6), (lat: 79.0, lon: 16.1)]
echo df.unnest("den")
echo df.unnest("den", separator = "_").columns
shape: (2, 3)
┌──────┬──────┬──────┐
│ bear ┆ lat ┆ lon │
│ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 │
╞══════╪══════╪══════╡
│ Ada ┆ 78.2 ┆ 15.6 │
│ Bo ┆ 79.0 ┆ 16.1 │
└──────┴──────┴──────┘
@["bear", "den_lat", "den_lon"]
- WHEN a list column is unnested
- THEN
InvalidOperationErrororSchemaErroris raised
Value counts as an expression
e.valueCounts(sort, parallel, name, normalize) SHALL give a struct column with the distinct values and their counts (or fractions with normalize), named count (or proportion) unless name is given.
let df = newDataFrame:
island: ["Biscoe", "Dream", "Biscoe"]
echo df.select(col("island").valueCounts(sort = true)).unnest("island")
shape: (2, 2)
┌────────┬───────┐
│ island ┆ count │
│ --- ┆ --- │
│ str ┆ u32 │
╞════════╪═══════╡
│ Biscoe ┆ 2 │
│ Dream ┆ 1 │
└────────┴───────┘
- WHEN
valueCounts(sort = true)is evaluated - THEN the most frequent value comes first
Array functions
e.arr SHALL give a namespace of functions on each array of an Array column: len, sum, min, max, mean, median, std, var, argMin, argMax, first, last, get, join, contains, countMatches, sort, slice, head, tail, shift, toList, toStruct, explode, eval and agg.
let df = newDataFrame:
rgb: [[255, 0, 0], [10, 20, 30]]
echo df.select(col("rgb").arr.sum.alias("sum"), col("rgb").arr.get(1).alias("g"),
col("rgb").arr.toList.alias("list"))
shape: (2, 3)
┌─────┬─────┬──────────────┐
│ sum ┆ g ┆ list │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ list[i64] │
╞═════╪═════╪══════════════╡
│ 255 ┆ 0 ┆ [255, 0, 0] │
│ 60 ┆ 20 ┆ [10, 20, 30] │
└─────┴─────┴──────────────┘
- WHEN
arr.toStructis evaluated on arrays of width 3 - THEN the result is a struct with fields
field_0,field_1andfield_2
Structs from column names
asStruct SHALL also take column names: asStruct("a", "b") is asStruct(col("a"), col("b")) (Python's pl.struct("a", "b")).
let df = newDataFrame:
bear: ["Ada", "Bo"]
kg: [410, 380]
echo df.select(asStruct("bear", "kg").alias("s"))
shape: (2, 1)
┌─────────────┐
│ s │
│ --- │
│ struct[2] │
╞═════════════╡
│ {"Ada",410} │
│ {"Bo",380} │
└─────────────┘
- WHEN
asStruct("bear", "kg")is selected - THEN the struct has the fields bear and kg
temporal
Purpose: Dates, datetimes, durations and times of day: Nim values, constructors, parsing strings, and the dt namespace.
Temporal values
The API SHALL provide Date (date(y, m, d)) and TimeOfDay (timeOfDay(h, m, s, ns)), and SHALL accept them and std/times' DateTime and Duration wherever Nim values build columns or literals. toList and df[c, i, T] SHALL read them back, as Option for nulls. DateTime values SHALL be stored and read back as UTC instants. nanuq SHALL export std/times.
let df = newDataFrame:
rider: ["Seixas", "Pogačar"]
born: [date(2006, 9, 24), date(1998, 9, 21)]
start: [timeOfDay(13, 10), timeOfDay(13, 12)]
gap: [initDuration(minutes = 4, seconds = 23), initDuration()]
finish: [dateTime(2026, mJul, 4, 17, 21, zone = utc()), nil]
echo df
echo df.filter(col.born > date(2000, 1, 1)).toList("rider", string)
echo df.toList("born", Date)[0].year, " ", df["finish", 1, Option[DateTime]].isNone
shape: (2, 5)
┌─────────┬────────────┬──────────┬──────────────┬─────────────────────┐
│ rider ┆ born ┆ start ┆ gap ┆ finish │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ date ┆ time ┆ duration[μs] ┆ datetime[μs] │
╞═════════╪════════════╪══════════╪══════════════╪═════════════════════╡
│ Seixas ┆ 2006-09-24 ┆ 13:10:00 ┆ 4m 23s ┆ 2026-07-04 17:21:00 │
│ Pogačar ┆ 1998-09-21 ┆ 13:12:00 ┆ 0µs ┆ null │
└─────────┴────────────┴──────────┴──────────────┴─────────────────────┘
@["Seixas"]
2006 true
- WHEN a column built from
[date(2026, 7, 4), nil]is read withtoList(df, c, Option[Date]) - THEN the result is
@[some(date(2026, 7, 4)), none(Date)]
- WHEN
timeOfDay(24)is called - THEN
ValueErroris raised
- WHEN a Date column is read with
toList(df, c, DateTime) - THEN
InvalidOperationErroris raised
Temporal ranges and durations
dateRange(start, stop, interval = "1d", closed = ClosedWindow.Both) and datetimeRange(..., timeUnit, timeZone) SHALL return expressions. interval SHALL be a Polars interval string or a TimeInterval, converted by toPolarsInterval, which raises ValueError on mixed signs. duration(weeks, days, hours, ..., nanoseconds) SHALL build a Duration from ints or expressions.
let months = newDataFrame().select(dateRange(date(2026, 1, 31), date(2026, 4, 30), 1.months).alias("day"))
echo months.toList("day", Date)
echo toPolarsInterval(1.years + 2.days)
let gaps = newDataFrame:
h: [73, 0]
m: [56, 4]
echo gaps.select(duration(hours = col.h, minutes = col.m, seconds = 26).alias("gap"))
@[2026-01-31, 2026-02-28, 2026-03-31, 2026-04-30]
1y2d
shape: (2, 1)
┌───────────────┐
│ gap │
│ --- │
│ duration[μs] │
╞═══════════════╡
│ 3d 1h 56m 26s │
│ 4m 26s │
└───────────────┘
- WHEN
dateRange(date(2026, 1, 31), date(2026, 4, 30), 1.months)is selected - THEN the dates are the last days of January to April
- WHEN
dateRange(date(2026, 1, 1), date(2026, 1, 15), "1w", closed = ClosedWindow.Left)is selected - THEN the result has 2 rows
- WHEN
toPolarsInterval(1.days - 2.hours)is called - THEN
ValueErroris raised
Parsing strings
e.str SHALL provide strptime(T, format, strict = true, exact = true, cache = true) for T in Date, DateTime and TimeOfDay, and the shorthands toDate(format), toDatetime(format, timeUnit, timeZone, ambiguous) and toTime(format). Formats SHALL use chrono's codes; an empty format SHALL let Polars infer it. A strict parse SHALL raise PolarsError when a value does not match; a non-strict one SHALL give null. exact = false SHALL allow the format to match part of the string.
let df = newDataFrame:
born: ["17 July 1993", "24 September 2006", "smudged"]
echo df.select(col.born.str.toDate("%d %B %Y", strict = false))
shape: (3, 1)
┌────────────┐
│ born │
│ --- │
│ date │
╞════════════╡
│ 1993-07-17 │
│ 2006-09-24 │
│ null │
└────────────┘
- WHEN
str.toDate("%d %B %Y")runs over a value "smudged" - THEN
PolarsErroris raised
- WHEN
str.toDatetime("%Y-%m-%d %H:%M", timeZone = "Australia/Adelaide")is selected - THEN the dtype is
datetime[μs, Australia/Adelaide]
Date and time parts
e.dt SHALL return a DtNameSpace with year, isoYear, quarter, month, week, weekday (Monday 1 to Sunday 7), day, ordinalDay, hour, minute, second, millisecond, microsecond, nanosecond, date, time, isLeapYear, daysInMonth, monthStart and monthEnd, each returning an expression with Polars' result dtype.
let df = newDataFrame:
at: [dateTime(2026, mJul, 4, 13, 10, zone = utc()), dateTime(2024, mFeb, 29, zone = utc())]
echo df.select(col.at.dt.year.alias("y"), col.at.dt.weekday.alias("wd"),
col.at.dt.ordinalDay.alias("od"), col.at.dt.date.alias("d"),
col.at.dt.time.alias("t"), col.at.dt.isLeapYear.alias("leap"))
shape: (2, 6)
┌──────┬─────┬─────┬────────────┬──────────┬───────┐
│ y ┆ wd ┆ od ┆ d ┆ t ┆ leap │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i32 ┆ i8 ┆ i16 ┆ date ┆ time ┆ bool │
╞══════╪═════╪═════╪════════════╪══════════╪═══════╡
│ 2026 ┆ 6 ┆ 185 ┆ 2026-07-04 ┆ 13:10:00 ┆ false │
│ 2024 ┆ 4 ┆ 60 ┆ 2024-02-29 ┆ 00:00:00 ┆ true │
└──────┴─────┴─────┴────────────┴──────────┴───────┘
- WHEN
dt.dayanddt.hourrun over 2026-07-04 13:10 - THEN the results are 4 and 13
- WHEN
dt.yearruns over a string column - THEN
PolarsErroris raised when the query runs
Formatting temporal values
dt.toString(format) and its alias dt.strftime(format) SHALL format dates, datetimes and times with chrono's codes. dt.toString(DurationFormat.Iso) and dt.toString(DurationFormat.Polars) SHALL format durations as ISO 8601 or Polars' short form.
let df = newDataFrame:
at: [dateTime(2026, mJul, 4, 13, 10, zone = utc())]
gap: [initDuration(minutes = 4, seconds = 23)]
echo df.select(col.at.dt.toString("%d %B %Y"), col.gap.dt.toString(DurationFormat.Iso).alias("iso"),
col.gap.dt.toString(DurationFormat.Polars).alias("short"))
shape: (1, 3)
┌──────────────┬─────────┬────────┐
│ at ┆ iso ┆ short │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str │
╞══════════════╪═════════╪════════╡
│ 04 July 2026 ┆ PT4M23S ┆ 4m 23s │
└──────────────┴─────────┴────────┘
- WHEN a 4 min 23 s duration is formatted with
DurationFormat.IsoandDurationFormat.Polars - THEN the results are "PT4M23S" and "4m 23s"
Temporal arithmetic
Subtracting dates or datetimes SHALL give a Duration. dt SHALL provide truncate(every), round(every), offsetBy(by) (intervals as strings or TimeIntervals), timestamp(timeUnit), castTimeUnit(timeUnit), and on durations totalDays … totalNanoseconds, whole numbers unless fractional = true.
let df = newDataFrame:
born: [date(2006, 9, 24), date(1998, 9, 21)]
race: [date(2026, 3, 21), date(2026, 3, 21)]
echo df.select((col.race - col.born).dt.totalDays.alias("days"),
col.born.dt.offsetBy(19.years).alias("turns_19"),
col.race.dt.truncate(1.months).alias("month"))
shape: (2, 3)
┌───────┬────────────┬────────────┐
│ days ┆ turns_19 ┆ month │
│ --- ┆ --- ┆ --- │
│ i64 ┆ date ┆ date │
╞═══════╪════════════╪════════════╡
│ 7118 ┆ 2025-09-24 ┆ 2026-03-01 │
│ 10043 ┆ 2017-09-21 ┆ 2026-03-01 │
└───────┴────────────┴────────────┘
- WHEN 2024-02-29 is offset by
1.years - THEN the result is 2025-02-28
- WHEN
dt.totalDays(fractional = true)runs over 36 hours - THEN the result is 1.5
Time zones
dt.replaceTimeZone(timeZone, ambiguous = Ambiguous.Raise, nonExistent = NonExistent.Raise) SHALL attach a zone to wall-clock times (or remove it with ""), dt.convertTimeZone(timeZone) SHALL show the same instants in another zone, and dt.combine(time) SHALL join a date and a time of day into a datetime.
let stage = newDataFrame:
day: [date(2026, 1, 20)]
finish: [timeOfDay(14, 3)]
let local = col.day.dt.combine(col.finish).dt.replaceTimeZone("Australia/Adelaide")
echo stage.select(local.alias("adelaide"), local.dt.convertTimeZone("Europe/Paris").alias("paris"))
shape: (1, 2)
┌─────────────────────────────────┬────────────────────────────┐
│ adelaide ┆ paris │
│ --- ┆ --- │
│ datetime[μs, ┆ datetime[μs, Europe/Paris] │
│ Australia/Adelaide] ┆ │
╞═════════════════════════════════╪════════════════════════════╡
│ 2026-01-20 14:03:00 ACDT ┆ 2026-01-20 04:33:00 CET │
└─────────────────────────────────┴────────────────────────────┘
- WHEN 14:03 in Adelaide on 2026-01-20 is converted to Europe/Paris
- THEN the time is 04:33 and the value read back equals 03:33 UTC
- WHEN
dt.convertTimeZone("Mars/Olympus")runs - THEN
PolarsErroris raised
Dates from parts
date(year, month, day) SHALL build a Date column when at least one part is an expression; each part SHALL be an integer expression or a number, as Polars' date. Invalid dates (month 13, 30 February) SHALL raise when the query runs. With three numbers date SHALL keep returning a Date value.
let seasons = newDataFrame:
year: [1982, 1997, 2015]
month: [12, 11, 11]
echo seasons.select(date(col.year, col.month, 15).alias("mid"))
echo date(2026, 2, 1)
shape: (3, 1)
┌────────────┐
│ mid │
│ --- │
│ date │
╞════════════╡
│ 1982-12-15 │
│ 1997-11-15 │
│ 2015-11-15 │
└────────────┘
2026-02-01
- WHEN
date(col.year, 1, 1)runs on years 1950 and 1951 - THEN the result is the dates 1950-01-01 and 1951-01-01
- WHEN
date(col.year, 2, 30)runs - THEN a
PolarsErroris raised
More date parts and time ranges
dt.epoch(EpochUnit) SHALL give the time since 1970-01-01 (whole seconds and days for Seconds and Days), dt.century and dt.millennium the century and millennium, dt.dstOffset and dt.baseUtcOffset the offsets of zoned datetimes as Durations. timeRange(start, stop, interval, closed) SHALL give times of day, timeRanges one list per row.
let df = newDataFrame(series("d", @[date(2000, 6, 1), date(2001, 1, 1)]))
echo df.select(col("d").dt.epoch(EpochUnit.Days).alias("days"),
col("d").dt.century.alias("century"))
echo select(timeRange(timeOfDay(9), timeOfDay(11), "1h").alias("t"))
shape: (2, 2)
┌───────┬─────────┐
│ days ┆ century │
│ --- ┆ --- │
│ i32 ┆ i32 │
╞═══════╪═════════╡
│ 11109 ┆ 20 │
│ 11323 ┆ 21 │
└───────┴─────────┘
shape: (3, 1)
┌──────────┐
│ t │
│ --- │
│ time │
╞══════════╡
│ 09:00:00 │
│ 10:00:00 │
│ 11:00:00 │
└──────────┘
- WHEN
dt.dstOffsetruns on 2026-07-01 12:00 in Europe/Rome - THEN the result is 1 hour
Business days
dt.addBusinessDays(n, weekMask, holidays, roll), dt.isBusinessDay(weekMask, holidays) and businessDayCount(start, stop, weekMask, holidays) SHALL count business days: Monday to Friday by default (weekMask, Monday first), minus holidays. roll SHALL say what a start date that is not a business day does (Raise, Forward, Backward).
let df = newDataFrame(series("d", @[date(2026, 10, 30)]))
echo df.select(col("d").dt.addBusinessDays(1).alias("next"),
col("d").dt.isBusinessDay.alias("business"))
echo select(businessDayCount(date(2026, 11, 2), date(2026, 11, 9)).alias("n")).toList("n", int)
shape: (1, 2)
┌────────────┬──────────┐
│ next ┆ business │
│ --- ┆ --- │
│ date ┆ bool │
╞════════════╪══════════╡
│ 2026-11-02 ┆ true │
└────────────┴──────────┘
@[5]
- WHEN one business day is added to Friday 2026-10-30 with Monday 2026-11-02 a holiday
- THEN the result is 2026-11-03
temporal-grouping
Purpose: Grouping rows by time windows (dynamic and rolling group-by) and joining each row to the nearest row of another frame by a sorted key (as-of join).
Dynamic group-by
groupByDynamic(indexColumn, every, period, offset, ...) on a DataFrame or LazyFrame SHALL group the rows of the sorted indexColumn into windows that start every every, span period (default every) and are shifted by offset, labelled as label says, and agg SHALL aggregate each window. Intervals SHALL be std/times intervals or Polars duration strings; groupBy SHALL group within the windows.
let df = newDataFrame:
day: [date(2026, 1, 1), date(2026, 1, 20), date(2026, 2, 3), date(2026, 3, 30)]
rain: [12, 3, 40, 7]
echo df.groupByDynamic("day", every = 1.months).agg(col.rain.sum)
shape: (3, 2)
┌────────────┬──────┐
│ day ┆ rain │
│ --- ┆ --- │
│ date ┆ i64 │
╞════════════╪══════╡
│ 2026-01-01 ┆ 15 │
│ 2026-02-01 ┆ 40 │
│ 2026-03-01 ┆ 7 │
└────────────┴──────┘
- WHEN
groupByDynamic("day", every = 1.months, period = 3.months)aggregates monthly rows - THEN each window sums three months of rows
- WHEN
includeBoundaries = true - THEN the result has
_lower_boundaryand_upper_boundarycolumns
Rolling group-by
rolling(indexColumn, period, offset, closed = Right, groupBy) SHALL make one group per row, holding the rows whose indexColumn lies in the period up to that row's value (shifted by offset), and agg SHALL aggregate each group.
let df = newDataFrame:
day: [date(2026, 7, 1), date(2026, 7, 2), date(2026, 7, 5)]
rain: [4, 0, 10]
echo df.rolling("day", period = 3.days).agg(col.rain.sum.alias("rain_3d"))
shape: (3, 2)
┌────────────┬─────────┐
│ day ┆ rain_3d │
│ --- ┆ --- │
│ date ┆ i64 │
╞════════════╪═════════╡
│ 2026-07-01 ┆ 4 │
│ 2026-07-02 ┆ 4 │
│ 2026-07-05 ┆ 10 │
└────────────┴─────────┘
- WHEN rows on July 1, 2 and 5 are grouped with
period = 3.days - THEN the July 5 group holds only the July 5 row
As-of join
joinAsof(other, on, ...) (or leftOn and rightOn) SHALL join each left row to one right row by a sorted key: the last one at or before it (Backward), the first one at or after it (Forward) or the closest (Nearest), only within tolerance when given and only among rows with equal by columns; rows without a match SHALL get nulls. With coalesce = false the right key column SHALL be kept (with suffix if its name is taken), showing which right row matched.
let events = newDataFrame:
day: [date(2026, 1, 15), date(2026, 3, 2)]
event: ["flood", "drought"]
let oni = newDataFrame:
month: [date(2026, 1, 1), date(2026, 2, 1), date(2026, 3, 1)]
oni: [1.8, 1.5, 1.1]
echo events.joinAsof(oni, leftOn = "day", rightOn = "month")
shape: (2, 4)
┌────────────┬─────────┬────────────┬─────┐
│ day ┆ event ┆ month ┆ oni │
│ --- ┆ --- ┆ --- ┆ --- │
│ date ┆ str ┆ date ┆ f64 │
╞════════════╪═════════╪════════════╪═════╡
│ 2026-01-15 ┆ flood ┆ 2026-01-01 ┆ 1.8 │
│ 2026-03-02 ┆ drought ┆ 2026-03-01 ┆ 1.1 │
└────────────┴─────────┴────────────┴─────┘
- WHEN the nearest earlier right row is 2 days before and
tolerance = 1.days - THEN the left row gets nulls
- WHEN
joinAsof(other, on = "t", coalesce = false)runs - THEN the result has both
tandt_right
- WHEN
joinAsofis called withoutonand withoutleftOnandrightOn - THEN
ValueErroris raised
Group keys by name
The groupBy parameter of rolling and groupByDynamic SHALL take a column name, several names, an expression or several expressions (groupBy = "store", ["store", "aisle"], [col("store")]).
let df = newDataFrame(series("day", @[1, 2, 3, 1, 2]), series("store", @["a", "a", "a", "b", "b"]),
series("sales", @[1, 2, 3, 10, 20]))
echo df.rolling("day", "2i", groupBy = "store").agg(col("sales").sum)
shape: (5, 3)
┌───────┬─────┬───────┐
│ store ┆ day ┆ sales │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 │
╞═══════╪═════╪═══════╡
│ a ┆ 1 ┆ 1 │
│ a ┆ 2 ┆ 3 │
│ a ┆ 3 ┆ 5 │
│ b ┆ 1 ┆ 10 │
│ b ┆ 2 ┆ 30 │
└───────┴─────┴───────┘
- WHEN
groupBy = [col("store")]is passed - THEN the result is the same as with
groupBy = "store"
testing-helpers
Purpose: Assertions for tests that compare frames and series, in the module nanuq/testing, as polars.testing.
Comparing frames in tests
assertFrameEqual(left, right, checkRowOrder = true, checkColumnOrder = true, checkDtypes = true, checkExact = false, rtol = 1e-5, atol = 1e-8) in nanuq/testing SHALL return when the frames (or collected LazyFrames) have the same columns, types and rows, with nulls equal to nulls and floats equal within atol + rtol * abs(right) unless checkExact, and raise AssertionDefect naming the first difference otherwise. assertFrameNotEqual SHALL do the opposite.
import nanuq/testing
let df = newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.0, 380.5]))
assertFrameEqual(df, newDataFrame(series("bear", @["Ada", "Bo"]), series("kg", @[410.0, 380.5000001])))
try:
assertFrameEqual(df, newDataFrame(series("bear", @["Ada", "Cy"]), series("kg", @[410.0, 380.5])))
except AssertionDefect as e:
echo e.msg
DataFrame column "bear" values differ at row 1: Bo != Cy
- WHEN two frames hold the same rows and columns in another order and both order checks are off
- THEN
assertFrameEqualreturns
Comparing Series in tests
assertSeriesEqual(left, right, checkDtypes = true, checkNames = true, checkOrder = true, checkExact = false, rtol = 1e-5, atol = 1e-8) SHALL compare two Series the same way, also checking their names unless checkNames = false; assertSeriesNotEqual SHALL do the opposite.
import nanuq/testing
let a = series("kg", @[410, 380])
assertSeriesEqual(a, series("mass", @[410, 380]), checkNames = false)
assertSeriesNotEqual(a, series("kg", @[410, 381]))
echo "ok"
ok
- WHEN both Series hold NaN at the same row
- THEN
assertSeriesEqualreturns
value-functions
Purpose: Expressions that treat the values of a column as a sequence or a set: ordering, picking values by position or rank, distinct values, recoding, binning and counting.
Ordering values
e.sort(descending, nullsLast) SHALL sort the values of e, e.argSort SHALL return the row indices that sort them, e.sortBy(by, descending) SHALL order e by one or more other columns, and e.reverse SHALL reverse it, so that these work inside agg and over.
let df = newDataFrame:
basin: ["Pacific", "Pacific", "Atlantic", "Atlantic"]
storm: ["Ana", "Bud", "Cleo", "Dan"]
wind: [120, 185, 150, 95]
echo df.groupBy(col.basin).agg(col.storm.sortBy(col.wind, descending = true).first
.alias("strongest")).sort("basin")
shape: (2, 2)
┌──────────┬───────────┐
│ basin ┆ strongest │
│ --- ┆ --- │
│ str ┆ str │
╞══════════╪═══════════╡
│ Atlantic ┆ Cleo │
│ Pacific ┆ Bud │
└──────────┴───────────┘
- WHEN
col.x.sort(descending = true)is selected on 2, 3, 1 - THEN the result is 3, 2, 1
Picking values
e.head(n = 10), e.tail(n = 10), e.slice(offset, length), e.gather(indices), e.gatherEvery(n, offset = 0), e.topK(k = 5), e.bottomK(k = 5), e.topKBy(by, k = 5, reverse) and e.bottomKBy(...) SHALL return those values of e (the k ones in no particular order, as in Polars); e.indexOf(value) SHALL return the index of the first occurrence of value (or null), and e.searchSorted(element, side) the index at which element would be inserted to keep e sorted.
let df = newDataFrame:
year: [1982, 1997, 2015, 2023]
oni: [2.2, 2.4, 2.6, 2.0]
echo df.select(col.year.topKBy(col.oni, k = 2).sort.alias("top2"),
col.oni.topK(2).sort.alias("peak"))
shape: (2, 2)
┌──────┬──────┐
│ top2 ┆ peak │
│ --- ┆ --- │
│ i64 ┆ f64 │
╞══════╪══════╡
│ 1997 ┆ 2.4 │
│ 2015 ┆ 2.6 │
└──────┴──────┘
- WHEN
col.x.gather([0, 2])is selected on 10, 20, 30 - THEN the result is 10, 30
- WHEN
searchSorted(2)runs on 1, 2, 2, 3 with sideLeftandRight - THEN the results are 1 and 3
Distinct values
e.unique(maintainOrder = false) SHALL return the distinct values, isUnique, isDuplicated, isFirstDistinct and isLastDistinct SHALL flag rows by how their value repeats, argUnique SHALL return the index of each value's first occurrence, uniqueCounts the number of occurrences of each distinct value in order of appearance, and approxNUnique an estimate of the number of distinct values.
let df = newDataFrame:
station: ["Lima", "Quito", "Lima", "Paita"]
echo df.withColumns(col.station.isDuplicated.alias("dup"),
col.station.isFirstDistinct.alias("first"))
shape: (4, 3)
┌─────────┬───────┬───────┐
│ station ┆ dup ┆ first │
│ --- ┆ --- ┆ --- │
│ str ┆ bool ┆ bool │
╞═════════╪═══════╪═══════╡
│ Lima ┆ true ┆ true │
│ Quito ┆ false ┆ true │
│ Lima ┆ true ┆ false │
│ Paita ┆ false ┆ true │
└─────────┴───────┴───────┘
- WHEN
unique(maintainOrder = true)runs on b, a, b, c - THEN the result is b, a, c
Recoding values
e.replace(old, new) and e.replace({old: new, ...}) SHALL replace each listed value and keep the others and the data type; e.replaceStrict(...) SHALL require every value to be listed, unless a default is given, and SHALL take the data type of the new values.
let df = newDataFrame:
phase: ["N", "EN", "LN", "EN"]
echo df.withColumns(col.phase.replaceStrict({"EN": "El Niño", "LN": "La Niña"},
default = "neutral").alias("name"))
shape: (4, 2)
┌───────┬─────────┐
│ phase ┆ name │
│ --- ┆ --- │
│ str ┆ str │
╞═══════╪═════════╡
│ N ┆ neutral │
│ EN ┆ El Niño │
│ LN ┆ La Niña │
│ EN ┆ El Niño │
└───────┴─────────┘
- WHEN
replaceStrict({"a": 1})runs on a column holding "a" and "b" - THEN collecting raises
InvalidOperationError
- WHEN
replace([1, 2], [10])is built - THEN
ValueErroris raised
Binning
e.cut(breaks, labels, leftClosed = false) SHALL put each value in the interval between breaks it falls into, as an Enum labelled like "(-0.5, 0.5]" or with labels (one more than breaks), and e.qcut(quantiles, ...) SHALL do the same at the quantiles of the values, given as probabilities or as a number of equal groups.
let df = newDataFrame:
oni: [-1.6, -0.2, 0.3, 0.9, 2.4]
echo df.withColumns(col.oni.cut([-0.5, 0.5], labels = ["La Niña", "neutral", "El Niño"])
.alias("phase"))
shape: (5, 2)
┌──────┬─────────┐
│ oni ┆ phase │
│ --- ┆ --- │
│ f64 ┆ enum │
╞══════╪═════════╡
│ -1.6 ┆ La Niña │
│ -0.2 ┆ neutral │
│ 0.3 ┆ neutral │
│ 0.9 ┆ El Niño │
│ 2.4 ┆ El Niño │
└──────┴─────────┘
- WHEN
cut([0.0])runs on -1.0 and 1.0 - THEN the labels are "(-inf, 0]" and "(0, inf]"
Value counts
valueCounts(column, sort = false, normalize = false, name) on a DataFrame or LazyFrame SHALL return each distinct value of column with its number of occurrences in a column count (or its share in proportion with normalize, or the column name), most frequent first with sort.
let df = newDataFrame:
phase: ["neutral", "El Niño", "neutral", "La Niña", "neutral", "El Niño"]
echo df.valueCounts("phase", sort = true)
shape: (3, 2)
┌─────────┬───────┐
│ phase ┆ count │
│ --- ┆ --- │
│ str ┆ u32 │
╞═════════╪═══════╡
│ neutral ┆ 3 │
│ El Niño ┆ 2 │
│ La Niña ┆ 1 │
└─────────┴───────┘
- WHEN
valueCounts("x", normalize = true)runs on a, a, b, b - THEN each value has proportion 0.5
Top k rows
LazyFrame and DataFrame SHALL support topK(k, by, reverse = false) and bottomK(k, by, reverse = false), returning the k whole rows with the largest (topK) or smallest (bottomK) values of by, in that order. by SHALL be a column name, a list of names, an expression or a list of expressions; with several keys the later ones break ties. reverse = true SHALL swap the direction. Nulls SHALL come last and ties SHALL keep their original order.
let events = newDataFrame:
start: ["1972 MJJ", "1982 AMJ", "1997 AMJ", "2015 MAM", "2023 MJJ"]
peak: [2.1, 2.2, 2.4, 2.6, 2.0]
echo events.topK(3, by = "peak")
echo events.bottomK(1, by = col.peak)
shape: (3, 2)
┌──────────┬──────┐
│ start ┆ peak │
│ --- ┆ --- │
│ str ┆ f64 │
╞══════════╪══════╡
│ 2015 MAM ┆ 2.6 │
│ 1997 AMJ ┆ 2.4 │
│ 1982 AMJ ┆ 2.2 │
└──────────┴──────┘
shape: (1, 2)
┌──────────┬──────┐
│ start ┆ peak │
│ --- ┆ --- │
│ str ┆ f64 │
╞══════════╪══════╡
│ 2023 MJJ ┆ 2.0 │
└──────────┴──────┘
- WHEN
topK(2, by = "peak", reverse = true)runs - THEN it returns the same rows as
bottomK(2, by = "peak")
- WHEN
topK(10, by = "peak")runs on 5 rows - THEN all 5 rows are returned, largest first
Source files
Every source file this page mentions, folded: tap one to read it. A file's name in the text leads here.
tools/specview.nim: the report on this page 843 lines
## specview: a review page for the OpenSpec changes in this repository.
##
## Reads `openspec/` (changes, archive, main specs), `BACKLOG.md` and, with `--base`,
## git, and writes one self-contained HTML page:
## - where each change is in the process (proposal → specs → design → tasks →
## implementation → archive),
## - its proposal, design and tasks, and its revisions (each commit that touched it,
## shown as word diffs of the changed paragraphs),
## - its spec deltas as requirement cards, with MODIFIED requirements shown as a word
## diff against the current spec,
## - with `--base`, a line diff of every OpenSpec, backlog and changelog file changed
## since that git ref,
## - every main spec in full (`openspec/specs/`), with its requirements, examples and
## scenarios, marking the specs that active changes touch.
##
## Archived changes are hidden until "Show archived changes" is ticked, except those
## changed since `--base`.
##
## Usage:
## nim r tools/specview.nim [--base:origin/main] [--out:specview.html] [--md:summary.md]
##
## Only the standard library is used, so it runs without the Rust build.
import std/[os, osproc, strutils, tables, algorithm, parseopt, sequtils, times]
import experimental/diff
# ---------------------------------------------------------------------------
# Model and parsing
# ---------------------------------------------------------------------------
type
Scenario = object
name: string
lines: seq[string]
Requirement = object
name: string
body: string
scenarios: seq[Scenario]
Section = object
title: string ## "Requirements", "ADDED Requirements", ...
reqs: seq[Requirement]
SpecDoc = object
purpose: string
sections: seq[Section]
Task = object
id, text: string
done: bool
TaskGroup = object
title: string
tasks: seq[Task]
CapDelta = object
name: string
delta: SpecDoc
current: SpecDoc
isNew: bool
Change = object
name, dir: string
archived: bool
created: string
proposal, design: string
hasProposal, hasDesign, hasTasks: bool
tasks: seq[TaskGroup]
caps: seq[CapDelta]
backlog: seq[string] ## titles of BACKLOG.md entries naming this change
touched: bool ## changed since --base
proc readOr(path: string, default = ""): string =
if fileExists(path): readFile(path) else: default
proc parseSpec(text: string): SpecDoc =
var section = -1
var inPurpose = false
var purpose: seq[string]
template curReq: untyped = result.sections[section].reqs[^1]
var inFence = false
for raw in text.splitLines:
let line = raw.strip(leading = false)
if line.strip.startsWith("```"): inFence = not inFence
if inFence or line.strip.startsWith("```"):
# code examples: kept verbatim, never read as headings
if section >= 0 and result.sections[section].reqs.len > 0 and curReq.scenarios.len == 0:
curReq.body.add line & "\n"
elif inPurpose: purpose.add line
elif line.startsWith("## "):
let title = line[3..^1].strip
inPurpose = title == "Purpose"
if not inPurpose:
result.sections.add Section(title: title)
section = result.sections.high
elif line.startsWith("### Requirement:"):
if section < 0:
result.sections.add Section(title: "Requirements")
section = 0
result.sections[section].reqs.add Requirement(name: line["### Requirement:".len..^1].strip)
elif line.startsWith("#### Scenario:"):
if section >= 0 and result.sections[section].reqs.len > 0:
curReq.scenarios.add Scenario(name: line["#### Scenario:".len..^1].strip)
elif line.startsWith("# "):
discard
elif inPurpose:
purpose.add line
elif section >= 0 and result.sections[section].reqs.len > 0:
if curReq.scenarios.len > 0:
if line.len > 0: curReq.scenarios[^1].lines.add line
else:
curReq.body.add line & "\n"
result.purpose = purpose.join("\n").strip
for s in result.sections.mitems:
for r in s.reqs.mitems: r.body = r.body.strip
proc parseTasks(text: string): seq[TaskGroup] =
for raw in text.splitLines:
let line = raw.strip
if line.startsWith("## "):
result.add TaskGroup(title: line[3..^1].strip)
elif line.startsWith("- [") and line.len > 4:
let close = line.find(']')
if close < 0: continue
if result.len == 0: result.add TaskGroup(title: "Tasks")
let mark = line[3 ..< close].strip
var rest = line[close + 1 .. ^1].strip
var id = ""
let sp = rest.find(' ')
if sp > 0 and rest[0].isDigit:
id = rest[0 ..< sp]
rest = rest[sp + 1 .. ^1]
result[^1].tasks.add Task(id: id, text: rest, done: mark.toLowerAscii == "x")
proc sectionsOf(md: string): OrderedTable[string, string] =
var cur = ""
for line in md.splitLines:
if line.startsWith("## "):
cur = line[3..^1].strip
result[cur] = ""
elif cur.len > 0:
result[cur].add line & "\n"
proc backlogEntries(backlog: string): seq[(string, string)] =
## (title, full text) of every top-level "- **Title**" entry.
var title, body: string
for line in backlog.splitLines:
if line.startsWith("- **") or line.startsWith("## "):
if title.len > 0: result.add (title, body)
title = ""; body = ""
if line.startsWith("- **"):
let e = line.find("**", 4)
title = if e > 4: line[4 ..< e] else: line
if title.len > 0: body.add line & "\n"
if title.len > 0: result.add (title, body)
proc loadChange(root, dir: string, archived: bool, backlog: seq[(string, string)]): Change =
result.dir = dir.relativePath(root).replace('\\', '/')
result.archived = archived
result.name = dir.lastPathPart
if archived and result.name.len > 11 and result.name[10] == '-':
result.name = result.name[11..^1] # archive dirs are prefixed with a date
for line in readOr(dir / ".openspec.yaml").splitLines:
if line.startsWith("created:"): result.created = line[8..^1].strip
result.proposal = readOr(dir / "proposal.md")
result.design = readOr(dir / "design.md")
result.hasProposal = result.proposal.len > 0
result.hasDesign = result.design.len > 0
result.hasTasks = fileExists(dir / "tasks.md")
result.tasks = parseTasks(readOr(dir / "tasks.md"))
if dirExists(dir / "specs"):
for f in walkDirRec(dir / "specs"):
if f.endsWith("spec.md"):
let cap = f.parentDir.relativePath(dir / "specs")
let mainPath = root / "openspec" / "specs" / cap / "spec.md"
result.caps.add CapDelta(name: cap, delta: parseSpec(readFile(f)),
current: parseSpec(readOr(mainPath)),
isNew: not fileExists(mainPath))
result.caps.sort(proc (a, b: CapDelta): int = cmp(a.name, b.name))
for (title, body) in backlog:
if result.name in body: result.backlog.add title
proc taskCounts(c: Change): (int, int) =
for g in c.tasks:
for t in g.tasks:
inc result[1]
if t.done: inc result[0]
proc stage(c: Change): string =
let (done, total) = c.taskCounts
if c.archived: "Archived"
elif not (c.hasProposal and c.caps.len > 0 and c.hasTasks): "Planning"
elif done == 0: "Ready to apply"
elif done < total: "Implementing"
else: "Ready to archive"
# ---------------------------------------------------------------------------
# HTML helpers: escaping, a small Markdown subset, word and line diffs
# ---------------------------------------------------------------------------
proc esc(s: string): string =
result = newStringOfCap(s.len)
for ch in s:
case ch
of '&': result.add "&"
of '<': result.add "<"
of '>': result.add ">"
of '"': result.add """
else: result.add ch
proc inline(s: string): string =
## `code`, **bold**, *em*, [text](url); everything else escaped.
var i = 0
while i < s.len:
if s[i] == '`':
let e = s.find('`', i + 1)
if e > i:
result.add "<code>" & esc(s[i+1 ..< e]) & "</code>"; i = e + 1; continue
elif s[i] == '*' and i + 1 < s.len and s[i+1] == '*':
let e = s.find("**", i + 2)
if e > i:
result.add "<strong>" & inline(s[i+2 ..< e]) & "</strong>"; i = e + 2; continue
elif s[i] == '*' and i + 1 < s.len and s[i+1] != ' ':
let e = s.find('*', i + 1)
if e > i + 1:
result.add "<em>" & inline(s[i+1 ..< e]) & "</em>"; i = e + 1; continue
elif s[i] == '[':
let m = s.find("](", i)
let e = if m > 0: s.find(')', m) else: -1
if m > i and e > m and '\n' notin s[i..e]:
result.add "<a href=\"" & esc(s[m+2 ..< e]) & "\">" & inline(s[i+1 ..< m]) & "</a>"
i = e + 1; continue
result.add esc($s[i])
inc i
proc md(text: string): string =
## Headings, paragraphs, bullet/numbered lists (one level), fenced code.
var para: seq[string]
var list: seq[string]
var listTag = ""
var code: seq[string]
var inCode = false
var lang = ""
template flushPara() =
if para.len > 0: result.add "<p>" & inline(para.join(" ")) & "</p>\n"; para = @[]
template flushList() =
if list.len > 0:
result.add "<" & listTag & ">"
for it in list: result.add "<li>" & inline(it) & "</li>"
result.add "</" & listTag & ">\n"
list = @[]
for raw in text.splitLines:
let line = raw.strip(leading = false)
let s = line.strip
if s.startsWith("```"):
if inCode:
# a ```text block shows an example's output
let cls = if lang == "text": " class=\"out\"" else: ""
result.add "<pre" & cls & "><code>" & esc(code.join("\n")) & "</code></pre>\n"; code = @[]
else:
flushPara(); flushList()
lang = s[3..^1].strip
inCode = not inCode
elif inCode: code.add raw
elif s.startsWith("<!--"): discard
elif s.len == 0: flushPara(); flushList()
elif s.startsWith("#"):
flushPara(); flushList()
let level = min(s.len - s.strip(chars = {'#'}).len + 2, 6)
result.add "<h" & $level & ">" & inline(s.strip(chars = {'#', ' '})) & "</h" & $level & ">\n"
elif s.startsWith("- ") or s.startsWith("* ") or
(s.len > 2 and s[0].isDigit and (s.find(". ") in 1..3)):
flushPara()
let ordered = s[0].isDigit
let tag = if ordered: "ol" else: "ul"
if list.len > 0 and tag != listTag: flushList()
listTag = tag
list.add(if ordered: s[s.find(". ") + 2 .. ^1] else: s[2..^1])
elif list.len > 0 and raw.startsWith(" "): list[^1].add " " & s
else: para.add s
flushPara(); flushList()
proc tokens(s: string): seq[string] =
## Words and whitespace runs, so a diff can be rejoined exactly.
var cur = ""
for ch in s:
if cur.len > 0 and (ch in Whitespace) != (cur[^1] in Whitespace):
result.add cur; cur = ""
cur.add ch
if cur.len > 0: result.add cur
proc wordDiff(a, b: string): string =
let ta = tokens(a)
let tb = tokens(b)
var ids: Table[string, int]
proc idsOf(ts: seq[string]): seq[int] =
for t in ts: result.add ids.mgetOrPut(t, ids.len)
let items = diffInt(idsOf(ta), idsOf(tb))
var ia, ib = 0
for it in items:
while ia < it.startA: result.add esc(ta[ia]); inc ia; inc ib
if it.deletedA > 0: result.add "<del>" & esc(ta[it.startA ..< it.startA + it.deletedA].join) & "</del>"
if it.insertedB > 0: result.add "<ins>" & esc(tb[it.startB ..< it.startB + it.insertedB].join) & "</ins>"
ia = it.startA + it.deletedA
ib = it.startB + it.insertedB
while ia < ta.len: result.add esc(ta[ia]); inc ia
proc reqText(r: Requirement): string =
result = r.body
for s in r.scenarios:
result.add "\n\nScenario: " & s.name
for l in s.lines: result.add "\n" & l
proc lineDiff(a, b: string, context = 3): (string, int, int) =
## Unified diff rendered as table rows, plus added and removed line counts.
let la = if a.len == 0: @[] else: a.splitLines
let lb = if b.len == 0: @[] else: b.splitLines
let items = diffText(la.join("\n"), lb.join("\n"))
var rows = ""
var added, removed = 0
proc row(kind, na, nb, text: string): string =
"<tr class=\"" & kind & "\"><td class=\"ln\">" & na & "</td><td class=\"ln\">" & nb &
"</td><td class=\"tx\">" & esc(text) & "</td></tr>\n"
var ia = 0
var ib = 0
var lastShown = -1
for idx, it in items:
let from0 = max(ia, it.startA - context)
if from0 > lastShown + 1 and lastShown >= 0 or (lastShown < 0 and from0 > 0):
rows.add "<tr class=\"gap\"><td class=\"ln\"></td><td class=\"ln\"></td><td class=\"tx\">⋯</td></tr>\n"
ib += from0 - ia
ia = from0
while ia < it.startA:
rows.add row("eq", $(ia + 1), $(ib + 1), la[ia]); inc ia; inc ib
for k in 0 ..< it.deletedA:
rows.add row("rm", $(it.startA + k + 1), "", la[it.startA + k]); inc removed
for k in 0 ..< it.insertedB:
rows.add row("ad", "", $(it.startB + k + 1), lb[it.startB + k]); inc added
ia = it.startA + it.deletedA
ib = it.startB + it.insertedB
let nextStart = if idx < items.high: items[idx + 1].startA else: la.len
let upto = min(ia + context, nextStart)
while ia < upto:
rows.add row("eq", $(ia + 1), $(ib + 1), la[ia]); inc ia; inc ib
lastShown = ia - 1
if lastShown >= 0 and lastShown < la.len - 1:
rows.add "<tr class=\"gap\"><td class=\"ln\"></td><td class=\"ln\"></td><td class=\"tx\">⋯</td></tr>\n"
(rows, added, removed)
# ---------------------------------------------------------------------------
# Rendering
# ---------------------------------------------------------------------------
const varsCss = """
:root{--ice:#f3f7f9;--floe:#fff;--ink:#12222e;--mute:#5a6b77;--rule:#d5e1e8;--fjord:#0d6f86;
--add:#e3f4e6;--add-ink:#1f6b2c;--del:#fbe7e4;--del-ink:#a2321f;--mod:#fff2d6;--mod-ink:#8a5a00;
--display:"Familjen Grotesk","Helvetica Neue",Arial,sans-serif;--body:"Literata",Georgia,serif;
--mono:"JetBrains Mono",ui-monospace,Menlo,Consolas,monospace;color-scheme:light}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--ice:#0d161d;--floe:#121e27;
--ink:#e3ecf1;--mute:#93a6b3;--rule:#22323e;--fjord:#5cc4dc;--add:#12301b;--add-ink:#8fd19a;
--del:#3a1a16;--del-ink:#f0a092;--mod:#33290f;--mod-ink:#f0c868;color-scheme:dark}}
"""
## The page frame of the standalone page: ground, column, header, headings.
const pageCss = """
*{box-sizing:border-box}
body{margin:0;background:var(--ice);color:var(--ink);font:16px/1.6 var(--body);
padding:0 max(16px,env(safe-area-inset-left,0px))}
main,header.mast{max-width:62rem;margin:0 auto}
header.mast{padding:2.5rem 0 1.5rem;border-bottom:1px solid var(--rule)}
.eyebrow{font:600 .75rem/1 var(--mono);letter-spacing:.12em;text-transform:uppercase;color:var(--fjord)}
h1{font:700 clamp(2rem,6vw,3rem)/1.05 var(--display);margin:.5rem 0}
h2,h3,h4,h5{font-family:var(--display);line-height:1.2}
h2{font-size:1.6rem;margin:2.5rem 0 .5rem}
h3{font-size:1.2rem;margin:1.6rem 0 .4rem}
.meta{font:.8rem/1.4 var(--mono);color:var(--mute)}
a{color:var(--fjord)}
footer{max-width:62rem;margin:3rem auto;color:var(--mute);font:.8rem var(--mono)}
"""
## The report itself (changes, requirements, diffs, specs). docs/openspec.nim reuses it
## inside the dev-log theme, scoped to `.specview`.
const reportCss* = """
code,pre{font-family:var(--mono);font-size:.85em}
p code,li code,td code{background:var(--rule);padding:.05em .3em;border-radius:3px}
pre{background:var(--floe);border:1px solid var(--rule);border-radius:6px;padding:.8rem;overflow-x:auto;line-height:1.25}
pre + pre.out{margin-top:-.4rem;border-top-left-radius:0;border-top-right-radius:0}
pre.out{background:var(--ice);border-style:dashed;position:relative}
pre.out::before{content:"output";position:absolute;top:.3rem;right:.6rem;font-size:.7rem;color:var(--mute);font-family:var(--display)}
table.overview{border-collapse:collapse;width:100%;font-size:.9rem;margin:1rem 0}
table.overview th,table.overview td{text-align:left;padding:.4rem .6rem;border-bottom:1px solid var(--rule);vertical-align:top}
table.overview th{font:600 .7rem/1 var(--mono);text-transform:uppercase;letter-spacing:.08em;color:var(--mute)}
.change{background:var(--floe);border:1px solid var(--rule);border-radius:10px;padding:1.2rem 1.4rem;margin:1.5rem 0}
.change>h2{margin-top:0}
.pill{display:inline-block;font:600 .7rem/1 var(--mono);letter-spacing:.06em;text-transform:uppercase;
padding:.35rem .55rem;border-radius:99px;border:1px solid var(--rule);color:var(--mute);vertical-align:middle;white-space:nowrap}
.pill.stage{background:var(--fjord);color:var(--floe);border-color:var(--fjord)}
.pill.touched{color:var(--mod-ink);background:var(--mod);border-color:transparent}
.steps{display:flex;flex-wrap:wrap;gap:.3rem;margin:1rem 0;padding:0;list-style:none}
.steps li{font:600 .72rem/1 var(--mono);padding:.5rem .7rem;border-radius:6px;border:1px solid var(--rule);color:var(--mute)}
.steps li.done{background:var(--add);color:var(--add-ink);border-color:transparent}
.steps li.now{background:var(--fjord);color:var(--floe);border-color:var(--fjord)}
.steps li.skip{border-style:dashed}
.bar{height:6px;background:var(--rule);border-radius:3px;overflow:hidden;margin:.3rem 0 .8rem}
.bar>span{display:block;height:100%;background:var(--fjord)}
details{border-top:1px solid var(--rule);padding:.5rem 0}
details>summary{cursor:pointer;font:700 1.05rem/1.4 var(--display);list-style-position:outside}
details>summary .meta{font-weight:400;margin-left:.5rem}
.cap{margin:1rem 0 1.5rem}
.cap>h4{margin:0 0 .5rem;font-size:1.05rem}
.req{border:1px solid var(--rule);border-left:4px solid var(--rule);border-radius:6px;padding:.7rem 1rem;margin:.6rem 0;background:var(--ice)}
.req.ADDED{border-left-color:var(--add-ink)}.req.MODIFIED{border-left-color:var(--mod-ink)}
.req.REMOVED{border-left-color:var(--del-ink)}.req.RENAMED{border-left-color:var(--fjord)}
.req .op{font:700 .65rem/1 var(--mono);letter-spacing:.08em;margin-right:.5rem}
.ADDED .op{color:var(--add-ink)}.MODIFIED .op{color:var(--mod-ink)}.REMOVED .op{color:var(--del-ink)}
.req h5{display:inline;font-size:1rem;margin:0}
.req p{margin:.4rem 0}
.scn{margin:.5rem 0 0;padding:.5rem .8rem;border-radius:4px;background:var(--floe);font-size:.92rem}
.scn b{font-family:var(--display)}
.scn ul{margin:.2rem 0;padding-left:1.1rem}
.wdiff{white-space:pre-wrap;font-size:.92rem;margin:.4rem 0}
ins{background:var(--add);color:var(--add-ink);text-decoration:none}
del{background:var(--del);color:var(--del-ink)}
.unchanged{color:var(--mute);font-size:.9rem}
.tasks{list-style:none;padding:0;margin:.3rem 0 1rem}
.tasks li{padding:.15rem 0 .15rem 1.7rem;position:relative}
.tasks li::before{content:"○";position:absolute;left:.3rem;color:var(--mute)}
.tasks li.done::before{content:"✓";color:var(--add-ink);font-weight:700}
.tasks li.done{color:var(--mute)}
.tid{font:.75rem var(--mono);color:var(--mute);margin-right:.3rem}
table.diff{border-collapse:collapse;width:100%;font:.78rem/1.45 var(--mono);background:var(--floe)}
table.diff td{padding:0 .5rem;vertical-align:top}
table.diff td.ln{color:var(--mute);text-align:right;width:3rem;user-select:none;border-right:1px solid var(--rule)}
table.diff td.tx{white-space:pre-wrap;word-break:break-word}
tr.ad{background:var(--add)}tr.ad td.tx::before{content:"+ ";color:var(--add-ink)}
tr.rm{background:var(--del)}tr.rm td.tx::before{content:"− ";color:var(--del-ink)}
tr.eq td.tx::before{content:" "}
tr.gap td{color:var(--mute);text-align:center}
.diffwrap{overflow-x:auto;border:1px solid var(--rule);border-radius:6px;margin:.5rem 0}
.count .a{color:var(--add-ink)}.count .r{color:var(--del-ink)}
.rev{margin:.8rem 0 1.2rem}
.revhead{margin-bottom:.4rem}
.revfile{margin:.6rem 0 .2rem;font-size:.9rem}
.hunk{border:1px solid var(--rule);border-radius:6px;padding:.5rem .8rem;margin:.4rem 0;background:var(--ice)}
.where{font:600 .7rem/1.2 var(--mono);color:var(--mute);text-transform:uppercase;letter-spacing:.06em;margin-bottom:.2rem}
.nav{display:flex;flex-wrap:wrap;gap:1rem;align-items:center;margin:1rem 0 0;font:600 .8rem/1 var(--mono)}
.nav label{color:var(--mute);cursor:pointer;display:inline-flex;gap:.4rem;align-items:center}
.archived{display:none}
body:has(#show-archived:checked) .archived,body.show-archived .archived{display:revert}
.hint{font:.8rem/1.4 var(--mono);color:var(--mute)}
.spec{background:var(--floe);border:1px solid var(--rule);border-radius:10px;padding:.6rem 1.4rem;margin:.8rem 0}
.spec>summary{font-size:1.15rem}
.req.CURRENT{border-left-color:var(--fjord)}
.speclist{columns:2 16rem;font-size:.9rem;padding-left:1.1rem}
"""
const css = varsCss & pageCss & reportCss
const toggleJs* = """<script>
(function(){
var box = document.getElementById("show-archived"), key = "specview-show-archived";
function apply(on){ document.body.classList.toggle("show-archived", on); box.checked = on; }
var saved = false;
try { saved = localStorage.getItem(key) === "1"; } catch(e) {}
apply(saved);
box.addEventListener("change", function(){
apply(box.checked);
try { localStorage.setItem(key, box.checked ? "1" : "0"); } catch(e) {}
});
// a link to an archived change or a spec opens it
function reveal(){
var id = decodeURIComponent(location.hash.slice(1)); if (!id) return;
var el = document.getElementById(id); if (!el) return;
if (el.classList.contains("archived")) apply(true);
if (el.tagName === "DETAILS") el.open = true;
el.scrollIntoView();
}
window.addEventListener("hashchange", reveal); reveal();
})();
</script>"""
proc deltaCounts(c: CapDelta): Table[string, int] =
for s in c.delta.sections:
result[s.title.split(' ')[0]] = result.getOrDefault(s.title.split(' ')[0]) + s.reqs.len
proc countsLabel(c: CapDelta): string =
var parts: seq[string]
let t = c.deltaCounts
for (k, sym) in [("ADDED", "+"), ("MODIFIED", "~"), ("REMOVED", "−"), ("RENAMED", "→")]:
if t.getOrDefault(k) > 0: parts.add sym & $t[k]
parts.join(" ")
proc renderScenarios(r: Requirement): string =
for s in r.scenarios:
result.add "<div class=\"scn\"><b>Scenario: " & inline(s.name) & "</b><ul>"
for l in s.lines:
result.add "<li>" & inline(l.strip(chars = {'-', ' '})) & "</li>"
result.add "</ul></div>"
proc renderReq(op: string, r: Requirement, current: SpecDoc): string =
result.add "<div class=\"req " & op & "\">" &
(if op == "CURRENT": "" else: "<span class=\"op\">" & op & "</span>") & "<h5>" &
inline(r.name) & "</h5>"
if op == "MODIFIED":
var before: Requirement
var found = false
for s in current.sections:
for cr in s.reqs:
if cr.name.toLowerAscii.strip == r.name.toLowerAscii.strip:
before = cr; found = true
if found:
result.add "<div class=\"wdiff\">" & wordDiff(reqText(before), reqText(r)) & "</div>"
else:
result.add "<p class=\"unchanged\">⚠ No requirement with this name in the current spec, so archiving will fail.</p>" &
md(r.body) & renderScenarios(r)
else:
result.add md(r.body) & renderScenarios(r)
result.add "</div>\n"
proc renderCap(c: CapDelta): string =
result.add "<div class=\"cap\"><h4><code>" & esc(c.name) & "</code> " &
(if c.isNew: "<span class=\"pill touched\">new capability</span>" else: "<span class=\"pill\">modified</span>") &
" <span class=\"meta\">" & c.countsLabel & "</span></h4>"
if c.delta.purpose.len > 0: result.add "<p><em>Purpose:</em> " & inline(c.delta.purpose) & "</p>"
var changed: seq[string]
for s in c.delta.sections:
let op = s.title.split(' ')[0]
for r in s.reqs:
changed.add r.name.toLowerAscii
result.add renderReq(op, r, c.current)
if not c.isNew:
var same: seq[string]
for s in c.current.sections:
for r in s.reqs:
if r.name.toLowerAscii notin changed: same.add r.name
if same.len > 0:
result.add "<p class=\"unchanged\">Unchanged in this spec: " & same.mapIt(inline(it)).join(", ") & "</p>"
result.add "</div>"
proc renderSteps(c: Change): string =
let (done, total) = c.taskCounts
type St = tuple[label, cls: string]
let implCls = if c.archived or (total > 0 and done == total): "done"
elif done > 0: "now" else: ""
var steps: seq[St] = @[
("Proposal", if c.hasProposal: "done" else: "now"),
("Specs", if c.caps.len > 0: "done" elif c.hasProposal: "now" else: ""),
("Design", if c.hasDesign: "done" elif c.hasTasks: "skip" else: ""),
("Tasks", if c.hasTasks: "done" elif c.caps.len > 0: "now" else: ""),
("Implement " & $done & "/" & $total, implCls),
("Archive", if c.archived: "done" elif total > 0 and done == total: "now" else: "")]
if c.hasProposal and c.caps.len > 0 and c.hasTasks and done == 0 and not c.archived:
steps[4].cls = "now"
result = "<ol class=\"steps\">"
for s in steps: result.add "<li class=\"" & s.cls & "\">" & esc(s.label) & "</li>"
result.add "</ol>"
proc git(root: string, args: varargs[string]): (string, int) =
execCmdEx("git -C " & quoteShell(root) & " " & args.mapIt(quoteShell(it)).join(" "))
proc paragraphs(text: string): seq[string] =
for p in text.replace("\r\n", "\n").split("\n\n"):
if p.strip.len > 0: result.add p.strip(chars = {'\n'})
proc paraDiff(a, b: string): string =
## Changed paragraphs only, each as a word diff, labelled with the nearest heading.
let pa = paragraphs(a)
let pb = paragraphs(b)
var ids: Table[string, int]
proc idsOf(ps: seq[string]): seq[int] =
for p in ps: result.add ids.mgetOrPut(p, ids.len)
for it in diffInt(idsOf(pa), idsOf(pb)):
var where = ""
let first = if it.startB < pb.len and pb[it.startB].startsWith("#"): it.startB else: it.startB - 1
for k in countdown(min(first, pb.high), 0):
if pb[k].startsWith("#"):
where = pb[k].strip(chars = {'#', ' '}).splitLines[0]; break
let before = pa[it.startA ..< it.startA + it.deletedA].join("\n\n")
let after = pb[it.startB ..< it.startB + it.insertedB].join("\n\n")
result.add "<div class=\"hunk\">" &
(if where.len > 0: "<div class=\"where\">§ " & esc(where) & "</div>" else: "") &
"<div class=\"wdiff\">" & wordDiff(before, after) & "</div></div>"
type Revision = object
label, sha, date, subject: string
proc revisions(root, dir: string): seq[Revision] =
let (log, code) = git(root, "log", "--reverse", "--format=%h%x09%ad%x09%s", "--date=short", "--", dir)
if code != 0: return
for line in log.splitLines:
let f = line.split('\t', 2)
if f.len == 3: result.add Revision(sha: f[0], date: f[1], subject: f[2])
let (dirty, _) = git(root, "status", "--porcelain", "--", dir)
if dirty.strip.len > 0:
result.add Revision(sha: "", date: "", subject: "uncommitted changes in the working tree")
for i, r in result.mpairs: r.label = "r" & $(i + 1)
proc fileAt(root, sha, path: string): string =
if sha.len == 0: return readOr(root / path)
let (s, code) = git(root, "show", sha & ":" & path)
if code == 0: s else: ""
proc renderRevisions(root: string, c: Change): string =
let revs = revisions(root, c.dir)
if revs.len == 0: return
result.add "<details" & (if revs.len > 1: " open" else: "") & "><summary>Revisions<span class=\"meta\">" &
$revs.len & (if revs.len == 1: " revision" else: " revisions") & "</span></summary>"
for i, r in revs:
result.add "<div class=\"rev\"><div class=\"revhead\"><span class=\"pill stage\">" & r.label &
"</span> <code>" & esc(if r.sha.len > 0: r.sha else: "working tree") & "</code> <span class=\"meta\">" &
esc(r.date) & "</span> " & inline(r.subject) & "</div>"
if i == 0:
let (files, _) = git(root, "ls-tree", "-r", "--name-only", (if r.sha.len > 0: r.sha else: "HEAD"), "--", c.dir)
let names = files.splitLines.filterIt(it.len > 0).mapIt(it.relativePath(c.dir))
result.add "<p class=\"unchanged\">First version: " & names.mapIt("<code>" & esc(it) & "</code>").join(", ") & "</p>"
else:
let prev = revs[i - 1].sha
let (files, _) = if r.sha.len > 0: git(root, "diff", "--name-only", prev, r.sha, "--", c.dir)
else: git(root, "diff", "--name-only", prev, "--", c.dir)
for f in files.splitLines:
if f.strip.len == 0: continue
result.add "<div class=\"revfile\"><code>" & esc(f.relativePath(c.dir)) & "</code></div>" &
paraDiff(fileAt(root, prev, f), fileAt(root, r.sha, f))
result.add "</div>"
result.add "</details>"
proc renderChange(c: Change, root: string): string =
let (done, total) = c.taskCounts
let hidden = c.archived and not c.touched
result.add "<section class=\"change" & (if hidden: " archived" else: "") & "\" id=\"" &
esc(c.name) & "\"><h2>" & esc(c.name) &
" <span class=\"pill stage\">" & c.stage & "</span>" &
(if c.touched: " <span class=\"pill touched\">changed in this diff</span>" else: "") & "</h2>"
result.add "<div class=\"meta\">" & (if c.created.len > 0: "created " & esc(c.created) & " · " else: "") &
esc(c.dir) & "</div>"
result.add renderSteps(c)
if c.backlog.len > 0:
result.add "<p><strong>From the backlog:</strong> " & c.backlog.mapIt(inline(it)).join("; ") & "</p>"
let ps = sectionsOf(c.proposal)
if c.hasProposal:
result.add "<details open><summary>Proposal</summary>"
for key in ["Why", "What Changes"]:
if key in ps: result.add "<h3>" & key & "</h3>" & md(ps[key])
for key, val in ps:
if key notin ["Why", "What Changes"]: result.add "<h3>" & esc(key) & "</h3>" & md(val)
result.add "</details>"
if c.caps.len > 0:
result.add "<details open><summary>Spec changes<span class=\"meta\">" &
c.caps.mapIt(esc(it.name) & " " & it.countsLabel).join(" · ") & "</span></summary>"
for cap in c.caps: result.add renderCap(cap)
result.add "</details>"
if c.hasDesign:
result.add "<details><summary>Design</summary>" & md(c.design) & "</details>"
if c.hasTasks:
result.add "<details " & (if done > 0 and done < total: "open" else: "") &
"><summary>Tasks<span class=\"meta\">" & $done & " of " & $total & " done</span></summary>"
for g in c.tasks:
let gd = g.tasks.countIt(it.done)
result.add "<h4>" & inline(g.title) & " <span class=\"meta\">" & $gd & "/" & $g.tasks.len & "</span></h4>"
if g.tasks.len > 0:
result.add "<div class=\"bar\"><span style=\"width:" & $(gd * 100 div g.tasks.len) & "%\"></span></div>"
result.add "<ul class=\"tasks\">"
for t in g.tasks:
result.add "<li class=\"" & (if t.done: "done" else: "") & "\"><span class=\"tid\">" & esc(t.id) &
"</span>" & inline(t.text) & "</li>"
result.add "</ul>"
result.add "</details>"
result.add renderRevisions(root, c)
result.add "</section>\n"
proc changedFiles(root, base: string): seq[string] =
let scope = ["openspec", "BACKLOG.md", "CHANGELOG.md"]
let (tracked, code) = git(root, @["diff", "--name-only", base, "--"] & @scope)
if code != 0: quit "git diff against " & base & " failed:\n" & tracked
let (untracked, _) = git(root, @["ls-files", "--others", "--exclude-standard", "--"] & @scope)
for l in (tracked & "\n" & untracked).splitLines:
if l.strip.len > 0 and l.strip notin result: result.add l.strip
result.sort
proc renderRawDiff(root, base: string, files: seq[string]): string =
result.add "<h2 id=\"raw-diff\">Files changed since <code>" & esc(base) & "</code></h2>"
if files.len == 0:
return result & "<p class=\"unchanged\">No OpenSpec, backlog or changelog files changed.</p>"
for f in files:
let (old, code) = git(root, "show", base & ":" & f)
let before = if code == 0: old else: ""
let after = readOr(root / f)
let (rows, added, removed) = lineDiff(before, after)
let tag = if code != 0: " <span class=\"pill touched\">new</span>"
elif not fileExists(root / f): " <span class=\"pill\">deleted</span>" else: ""
result.add "<details><summary><code>" & esc(f) & "</code>" & tag &
"<span class=\"meta count\"><span class=\"a\">+" & $added & "</span> <span class=\"r\">−" & $removed &
"</span></span></summary><div class=\"diffwrap\"><table class=\"diff\">" & rows & "</table></div></details>"
proc renderMarkdown(changes: seq[Change], base: string, files: seq[string]): string =
result = "## OpenSpec review\n\n"
let active = changes.filterIt(not it.archived)
if active.len == 0: result.add "No active changes.\n"
else:
result.add "| Change | Stage | Tasks | Specs |\n|---|---|---|---|\n"
for c in active:
let (done, total) = c.taskCounts
result.add "| " & (if c.touched: "**" & c.name & "**" else: c.name) & " | " & c.stage & " | " &
$done & "/" & $total & " | " &
c.caps.mapIt("`" & it.name & "` " & (if it.isNew: "(new) " else: "") & it.countsLabel).join(", ") & " |\n"
if base.len > 0:
result.add "\n" & $files.len & " OpenSpec/backlog/changelog files changed since `" & base & "`.\n"
result.add "\nThe full report (proposal, spec diffs, tasks, file diffs) is in this run's `specview` artifact.\n"
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
proc renderSpecs(root: string, changes: seq[Change], files: seq[string]): string =
## Every main spec in full; specs touched by an active change, or changed since
## --base, are marked.
var names: seq[string]
for kind, dir in walkDir(root / "openspec" / "specs"):
if kind == pcDir and fileExists(dir / "spec.md"): names.add dir.lastPathPart
names.sort
var pending = initTable[string, seq[string]]()
for c in changes:
if not c.archived:
for cap in c.caps: pending.mgetOrPut(cap.name, @[]).add c.name
result.add "<h2 id=\"specs\">Specs</h2><p class=\"hint\">The current specs in " &
"openspec/specs, as archived changes left them. Changes still open are not applied here.</p>"
result.add "<ul class=\"speclist\">"
for n in names:
result.add "<li><a href=\"#spec-" & esc(n) & "\"><code>" & esc(n) & "</code></a>" &
(if n in pending: " <span class=\"pill touched\">open change</span>" else: "") & "</li>"
result.add "</ul>"
for n in names:
let path = "openspec/specs/" & n & "/spec.md"
let doc = parseSpec(readFile(root / path))
var nreq = 0
for sec in doc.sections: nreq += sec.reqs.len
result.add "<details class=\"spec\" id=\"spec-" & esc(n) & "\"><summary><code>" & esc(n) &
"</code><span class=\"meta\">" & $nreq & " requirements" &
(if path in files: " · changed in this diff" else: "") &
(if n in pending: " · open change: " & pending[n].mapIt(esc(it)).join(", ") else: "") &
"</span></summary>"
if doc.purpose.len > 0: result.add "<p><em>Purpose:</em> " & inline(doc.purpose) & "</p>"
for sec in doc.sections:
for r in sec.reqs: result.add renderReq("CURRENT", r, doc)
result.add "</details>\n"
type Report* = object
## Everything specview reads: the changes, newest work first, and with a base the
## files changed since it.
root*, base*, head*: string
changes: seq[Change]
files: seq[string]
proc loadReport*(root: string, base = ""): Report =
result.root = root.absolutePath
result.base = base
let root = result.root
if not dirExists(root / "openspec"): quit "no openspec/ directory in " & root
let backlog = backlogEntries(readOr(root / "BACKLOG.md"))
for kind, dir in walkDir(root / "openspec" / "changes"):
if kind == pcDir and dir.lastPathPart != "archive":
result.changes.add loadChange(root, dir, false, backlog)
if dirExists(root / "openspec" / "changes" / "archive"):
for kind, dir in walkDir(root / "openspec" / "changes" / "archive"):
if kind == pcDir: result.changes.add loadChange(root, dir, true, backlog)
if base.len > 0:
result.files = changedFiles(root, base)
for c in result.changes.mitems:
c.touched = result.files.anyIt(it.startsWith(c.dir & "/"))
result.changes.sort(proc (a, b: Change): int =
result = cmp(a.archived, b.archived)
if result == 0: result = cmp(b.touched, a.touched)
if result == 0: result = cmp(a.name, b.name))
result.head = git(root, "log", "-1", "--format=%h %s")[0].strip
proc renderNav*(r: Report): string =
## Section links and the "Show archived changes" checkbox (needs `toggleJs`).
let base = r.base
"<nav class=\"nav\"><a href=\"#overview\">Changes</a><a href=\"#specs\">Specs</a>" &
(if base.len > 0: "<a href=\"#raw-diff\">Diff</a>" else: "") &
"<label><input type=\"checkbox\" id=\"show-archived\"> " &
(if base.len > 0: "Show older archived changes (" else: "Show archived changes (") &
$r.changes.countIt(it.archived and not it.touched) & ")</label></nav>" &
(if base.len > 0: "<p class=\"hint\">Compared with " & esc(base) &
": changes this branch added, edited or archived are always shown; archived " &
"changes it did not touch are hidden.</p>" else: "")
proc renderReport*(r: Report): string =
## The changes overview, every change, every spec and, with a base, the file diffs.
let active = r.changes.filterIt(not it.archived)
result.add "<h2 id=\"overview\">Changes</h2><table class=\"overview\"><tr><th>Change</th><th>Stage</th><th>Tasks</th><th>Specs</th></tr>"
for c in r.changes:
let (done, total) = c.taskCounts
result.add "<tr" & (if c.archived and not c.touched: " class=\"archived\"" else: "") &
"><td><a href=\"#" & esc(c.name) & "\">" & esc(c.name) & "</a>" &
(if c.touched: " <span class=\"pill touched\">changed</span>" else: "") & "</td><td>" & c.stage &
"</td><td>" & $done & "/" & $total & "</td><td>" &
c.caps.mapIt("<code>" & esc(it.name) & "</code> " & it.countsLabel).join("<br>") & "</td></tr>"
result.add "</table>"
if active.len == 0: result.add "<p class=\"unchanged\">No active changes.</p>"
for c in r.changes: result.add renderChange(c, r.root)
result.add renderSpecs(r.root, r.changes, r.files)
if r.base.len > 0: result.add renderRawDiff(r.root, r.base, r.files)
proc main() =
var root = getCurrentDir()
var base, outPath, mdPath = ""
outPath = "specview.html"
for kind, key, val in getopt():
case kind
of cmdLongOption, cmdShortOption:
case key
of "base": base = val
of "out": outPath = val
of "md": mdPath = val
of "root": root = val
of "help", "h":
echo "usage: specview [--root:DIR] [--base:GIT_REF] [--out:FILE.html] [--md:FILE.md]"; quit 0
else: quit "unknown option --" & key
else: discard
let r = loadReport(root, base)
var html = "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">" &
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>OpenSpec review</title>" &
"<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css2?family=Familjen+Grotesk:wght@500;700&family=Literata:ital,opsz,wght@0,7..72,400;0,7..72,600;1,7..72,400&family=JetBrains+Mono:wght@400;600&display=swap\">" &
"<style>" & css & "</style></head><body>"
html.add "<header class=\"mast\"><span class=\"eyebrow\">" & esc(r.root.lastPathPart) &
" · OpenSpec review</span><h1>Where the changes stand</h1><div class=\"meta\">" & esc(r.head) &
(if base.len > 0: " · compared with " & esc(base) else: "") & " · generated " &
now().format("yyyy-MM-dd HH:mm") & "</div>" & renderNav(r) & "</header><main>"
html.add renderReport(r)
html.add "</main><footer>Generated by tools/specview.nim</footer>" & toggleJs & "</body></html>\n"
writeFile(outPath, html)
echo "wrote ", outPath
if mdPath.len > 0:
let f = open(mdPath, fmAppend) # $GITHUB_STEP_SUMMARY is appended to
f.write renderMarkdown(r.changes, base, r.files)
f.close
echo "wrote ", mdPath
when isMainModule:
main()tools/specview.nim