Nanuq dev log Β· 1 November 2026

Designing Nanuq 0.5

Lists, structs, JSON, SQL and Nim procs that Polars calls back: the API choices 0.5 had to make, and what we picked.

API design Β· Nanuq 0.5 Β· built with Nanuq 0.6.1, Polars 2.1.0 and Nim 2.2.4 Β· rendered with nimib

The code this page talks about is folded under Source files, at the end.

Nanuq 0.5 is the release the roadmap called "nested data and user code". Until now a Nanuq column held one number, string, date or category per row. Now a cell can hold a list, a fixed-size array or a struct, and Polars can call your Nim procs. That unblocks most of what the Nanuq Book still marked "not yet": explode, str.split, struct.field, list.eval, valueCounts, unnest, readJson, mapElements, SQL.

It came in eight OpenSpec changes: nested data types, the list namespace, string functions that return lists, structs and arrays, JSON, SQL, Nim callbacks, and a bag of smaller functions. As before, most names are Polars' names in camelCase. This post is about the places where Nim and Polars disagree. Every snippet runs, on a few made-up rows about Alpine peaks above 4000 m (the subject of the 0.5 explainer).

import std/[options, strutils, streams]
import nanuq
let peaks = newDataFrame:
  peak: ["Mont Blanc", "Monte Rosa", "Gran Paradiso", "Weisshorn"]
  m: [4806, 4634, 4061, 4506]
  countries: [@["France", "Italy"], @["Italy", "Switzerland"], @["Italy"], @["Switzerland"]]
  huts: [@["GoΓ»ter", "Cosmiques"], @["Margherita"], @["Vittorio Emanuele", "Chabod"], @[]]
echo peaks
shape: (4, 4)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ peak          ┆ m    ┆ countries                ┆ huts                            β”‚
β”‚ ---           ┆ ---  ┆ ---                      ┆ ---                             β”‚
β”‚ str           ┆ i64  ┆ list[str]                ┆ list[str]                       β”‚
β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•ͺ══════β•ͺ══════════════════════════β•ͺ═════════════════════════════════║
β”‚ Mont Blanc    ┆ 4806 ┆ ["France", "Italy"]      ┆ ["GoΓ»ter", "Cosmiques"]         β”‚
β”‚ Monte Rosa    ┆ 4634 ┆ ["Italy", "Switzerland"] ┆ ["Margherita"]                  β”‚
β”‚ Gran Paradiso ┆ 4061 ┆ ["Italy"]                ┆ ["Vittorio Emanuele", "Chabod"… β”‚
β”‚ Weisshorn     ┆ 4506 ┆ ["Switzerland"]          ┆ []                              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

1. Nim types are Polars types, recursively↑ contents

0.2 settled that cast(float) and schema["m"] == Int64 use Nim types where Nim has them. 0.5 extends that to nested types:

Polars Nanuq data type Nim value
pl.List(pl.String) List(String) seq[string]
pl.Array(pl.Float64, 3) Array(Float64, 3) array[3, float]
pl.Struct({"x": pl.Int64}) Struct({"x": Int64}) an object or a named tuple

So dataType(seq[seq[int]]) == List(List(Int64)), and an object type maps to a Struct with one field per Nim field. DataType became a recursive variant object. Nim can't put a type inside itself directly, so the inner type lives in a one-element seq, and dt.inner hides that. Array(Int64, [2, 3]) is the same type as Array(Array(Int64, 3), 2), as in Polars, and shape gives @[2, 3] back.

How a data type prints. Until now $ gave Polars' short names, the ones in table headers: i64, list[str], struct[2]. Python prints something else: Int64, List(String), Struct({'x': Int64}). There were four options:

  1. Table-header names (list[str]): match the tables, but struct[2] hides the field names, and it is not what you write.
  2. Python's repr, exactly: matches df.schema in Python character for character, but Array(Float64, shape=(3,)) and single quotes are not Nim.
  3. Nanuq code: List(String), Array(Float64, 3), Struct({"x": Int64}). Nothing is hidden, you can paste it back into Nim, and it differs from Python only where Python's syntax is not Nim.
  4. Nim types (seq[string]): lossy, since Int32 and Int64 would both be int.

We picked 3. Temporal types print as the Nim types they cast to: Date, TimeOfDay, DateTime(Milliseconds, "Europe/Rome"). Table headers, glimpse and toHtml keep Polars' short names, as in Python.

echo peaks.schema
echo dataType(seq[seq[int]]), "  ", Array(Float64, [2, 3]), "  ",
     Struct({"lat": Float64, "lon": Float64})
{"peak": String, "m": Int64, "countries": List(String), "huts": List(String)}
List(List(Int64))  Array(Float64, [2, 3])  Struct({"lat": Float64, "lon": Float64})

2. Building and reading nested columns↑ contents

You build nested columns with plain Nim values, in newDataFrame, series or lit. There were three small choices:

To read them back you name the Nim type, as for any column: toList("huts", seq[string]). A list with nulls inside needs seq[Option[string]]. A null list needs Option[seq[string]]. If you ask for the plain type and there are nulls, toList raises InvalidOperationError.

type Summit = object
  lat: float
  lon: float
let summits = newDataFrame:
  peak: ["Mont Blanc", "Weisshorn"]
  at: [Summit(lat: 45.83, lon: 6.86), Summit(lat: 46.10, lon: 7.72)]
  rgb: [[255, 255, 255], [200, 210, 230]]
echo summits
echo peaks.toList("huts", seq[string])
echo summits.toList("at", Summit)
shape: (2, 3)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ peak       ┆ at           ┆ rgb             β”‚
β”‚ ---        ┆ ---          ┆ ---             β”‚
β”‚ str        ┆ struct[2]    ┆ array[i64, 3]   β”‚
β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•ͺ══════════════β•ͺ═════════════════║
β”‚ Mont Blanc ┆ {45.83,6.86} ┆ [255, 255, 255] β”‚
β”‚ Weisshorn  ┆ {46.1,7.72}  ┆ [200, 210, 230] β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
@[@["GoΓ»ter", "Cosmiques"], @["Margherita"], @["Vittorio Emanuele", "Chabod"], @[]]
@[(lat: 45.83, lon: 6.86), (lat: 46.1, lon: 7.72)]

3. element() and the list namespace↑ contents

The list namespace, col("huts").list, is about fifty functions with Polars' names: len, first, get, contains, join, sort, set operations and so on. The interesting part is list.eval, which runs an expression on the elements of each list. Python spells the element pl.element(), and so does Nanuq: element() is just a column with an empty name. list.agg is list.eval that must return one value per list.

echo peaks.select(
  col.peak,
  col.huts.list.len.alias("n_huts"),
  col.huts.list.first.alias("first_hut"),
  col.countries.list.contains("Italy").alias("in_italy"),
  col.countries.list.join(" / ").alias("border"),
  col.huts.list.eval(element().str.lenChars).alias("hut_name_lengths"))
shape: (4, 6)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ peak          ┆ n_huts ┆ first_hut         ┆ in_italy ┆ border              ┆ hut_name_lengths β”‚
β”‚ ---           ┆ ---    ┆ ---               ┆ ---      ┆ ---                 ┆ ---              β”‚
β”‚ str           ┆ u32    ┆ str               ┆ bool     ┆ str                 ┆ list[u32]        β”‚
β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•ͺ════════β•ͺ═══════════════════β•ͺ══════════β•ͺ═════════════════════β•ͺ══════════════════║
β”‚ Mont Blanc    ┆ 2      ┆ GoΓ»ter            ┆ true     ┆ France / Italy      ┆ [6, 9]           β”‚
β”‚ Monte Rosa    ┆ 1      ┆ Margherita        ┆ true     ┆ Italy / Switzerland ┆ [10]             β”‚
β”‚ Gran Paradiso ┆ 2      ┆ Vittorio Emanuele ┆ true     ┆ Italy               ┆ [17, 6]          β”‚
β”‚ Weisshorn     ┆ 0      ┆ null              ┆ false    ┆ Switzerland         ┆ []               β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

explode and implode go between lists and rows. On frames, explode takes column names, and an empty list gives a row with a null (Python's default; pass emptyAsNull = false to drop the row instead).

echo peaks.explode("countries").groupBy("countries")
  .agg(col.peak.alias("peaks"), col.m.max.alias("highest"))
  .sort("countries")
shape: (3, 3)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ countries   ┆ peaks                           ┆ highest β”‚
β”‚ ---         ┆ ---                             ┆ ---     β”‚
β”‚ str         ┆ list[str]                       ┆ i64     β”‚
β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•ͺ═════════════════════════════════β•ͺ═════════║
β”‚ France      ┆ ["Mont Blanc"]                  ┆ 4806    β”‚
β”‚ Italy       ┆ ["Mont Blanc", "Monte Rosa", "… ┆ 4806    β”‚
β”‚ Switzerland ┆ ["Monte Rosa", "Weisshorn"]     ┆ 4634    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

4. asStruct, because .struct is taken↑ contents

Python has a function pl.struct(...) that builds a struct and a namespace col("x").struct that reads one. Nim can't have both: in Nim, col("x").struct and struct(col("x")) are the same call. The namespace is used far more often, so it keeps the name, and the constructor is asStruct, its Rust name (as_struct).

Expr.valueCounts returns a struct column, as in Polars, and unnest turns its fields into columns. On frames, unnest(separator = "_") prefixes the field names, which is a Polars 1.x option.

let s = peaks.select(asStruct(col.peak, col.m).alias("summit"))
echo s.select(col.summit.struct.field("m"), col.summit.struct.jsonEncode.alias("json"))
echo peaks.explode("countries").select(col.countries.valueCounts(sort = true))
  .unnest("countries")
shape: (4, 2)
β”Œβ”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ m    ┆ json                            β”‚
β”‚ ---  ┆ ---                             β”‚
β”‚ i64  ┆ str                             β”‚
β•žβ•β•β•β•β•β•β•ͺ═════════════════════════════════║
β”‚ 4806 ┆ {"peak":"Mont Blanc","m":4806}  β”‚
β”‚ 4634 ┆ {"peak":"Monte Rosa","m":4634}  β”‚
β”‚ 4061 ┆ {"peak":"Gran Paradiso","m":40… β”‚
β”‚ 4506 ┆ {"peak":"Weisshorn","m":4506}   β”‚
β””β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
shape: (3, 2)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”
β”‚ countries   ┆ count β”‚
β”‚ ---         ┆ ---   β”‚
β”‚ str         ┆ u32   β”‚
β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•ͺ═══════║
β”‚ Italy       ┆ 3     β”‚
β”‚ Switzerland ┆ 2     β”‚
β”‚ France      ┆ 1     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜

5. String functions that return lists↑ contents

0.3 left out str.split, extractAll and extractGroups, because they return lists and structs. They are in now, with splitExact and splitn giving structs, as in Polars. replaceMany takes a Nim table literal, {"a": "x"}, like replace does since 0.4. jsonDecode takes either a DataType or a Nim type: jsonDecode(Summit).

let routes = newDataFrame:
  route: ["GoΓ»ter: 2 days, PD", "HΓΆrnli: 2 days, AD", "Normal: 1 day, F"]
echo routes.select(
  col.route.str.split(": ").list.first.alias("name"),
  col.route.str.extractGroups(r"(?<days>\d) days?, (?<grade>\w+)").alias("parts"))
  .unnest("parts")
shape: (3, 3)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”
β”‚ name   ┆ days ┆ grade β”‚
β”‚ ---    ┆ ---  ┆ ---   β”‚
β”‚ str    ┆ str  ┆ str   β”‚
β•žβ•β•β•β•β•β•β•β•β•ͺ══════β•ͺ═══════║
β”‚ GoΓ»ter ┆ 2    ┆ PD    β”‚
β”‚ HΓΆrnli ┆ 2    ┆ AD    β”‚
β”‚ Normal ┆ 1    ┆ F     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜

6. JSON and NDJSON↑ contents

readJson, readNdjson, scanNdjson, writeJson and writeNdjson take a path or a Nim Stream, like the CSV and Parquet functions. toJson and toNdjson return the text. Python's write_json() with no path also returns a string; in Nim a proc that sometimes writes and sometimes returns is awkward, so they are two names.

inferSchemaLength = none(int) reads every row to infer the schema, which matters for NDJSON with structs whose fields differ between rows.

let text = summits.select(col.peak, col.at).toNdjson
echo text
echo readNdjson(newStringStream(text)).unnest("at")
{"peak":"Mont Blanc","at":{"lat":45.83,"lon":6.86}}
{"peak":"Weisshorn","at":{"lat":46.1,"lon":7.72}}

shape: (2, 3)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”
β”‚ peak       ┆ lat   ┆ lon  β”‚
β”‚ ---        ┆ ---   ┆ ---  β”‚
β”‚ str        ┆ f64   ┆ f64  β”‚
β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•ͺ═══════β•ͺ══════║
β”‚ Mont Blanc ┆ 45.83 ┆ 6.86 β”‚
β”‚ Weisshorn  ┆ 46.1  ┆ 7.72 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”˜

7. SQL, with tables by variable name↑ contents

SQLContext mirrors Python: register, unregister, tables, execute. Python's execute(query, eager=True) returns a DataFrame and eager=False a LazyFrame. Nim procs have one return type, so here eager is a static bool: the compiler knows it and picks the return type. execute(q) alone gives a LazyFrame.

Python can also build a context from local variables, pl.SQLContext(frames=locals()). Nim has no locals(), but it has macros: sqlContext(peaks, routes) registers each frame under its variable name.

let ctx = sqlContext(peaks)
echo ctx.execute("""
    SELECT peak, m FROM peaks WHERE m > 4500 ORDER BY m DESC""", eager = true)
echo peaks.sql("SELECT COUNT(*) AS n, MAX(m) AS top FROM self")
shape: (3, 2)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”
β”‚ peak       ┆ m    β”‚
β”‚ ---        ┆ ---  β”‚
β”‚ str        ┆ i64  β”‚
β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•ͺ══════║
β”‚ Mont Blanc ┆ 4806 β”‚
β”‚ Monte Rosa ┆ 4634 β”‚
β”‚ Weisshorn  ┆ 4506 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”˜
shape: (1, 2)
β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”
β”‚ n   ┆ top  β”‚
β”‚ --- ┆ ---  β”‚
β”‚ i64 ┆ i64  β”‚
β•žβ•β•β•β•β•β•ͺ══════║
β”‚ 4   ┆ 4806 β”‚
β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”˜

8. Nim procs that Polars calls↑ contents

mapElements runs a Nim proc on each value. In Python the return type is guessed from the first results, or given with return_dtype. In Nim the proc's type says it all: proc (x: int): string reads Int64 and gives a String column. A proc that takes an object or a tuple gets each struct row as that type, and one that returns a seq gives a List column. Nulls are skipped, unless the proc takes an Option, as in Python's skip_nulls=True default.

mapBatches gets whole Series, and in a group-by it gets one group at a time, so it can aggregate (returnsScalar = true tells Polars it does). fold, reduce, cumFold, name.map and GroupBy.mapGroups work the same way.

Polars runs expressions on its own threads. The callbacks go through a lock, so only one Nim proc runs at a time, and Nim's memory management needs no setup. A Nim exception in a callback becomes a Polars ComputeError with the same message. It never crosses the C ABI as a Nim exception.

Is it faster than Python? Yes, but not by as much as "compiled" suggests. Python's map_elements calls a Python function once per value. Nanuq gets a whole batch, so the loop runs in compiled Nim. On a million rows (benchmarks/map_elements.nim and .py), Nanuq's mapElements is about 10x faster than py-polars for a number to number function, 4x for a struct row, and 2x for strings. What is left is copying: each batch is copied out of Arrow memory into Nim seqs (one allocation per string) and the results are copied into a new Series. That is why a native expression is still 5 to 12 times faster than mapElements, in Nanuq as in Python. Zero-copy columns through the Arrow C Data Interface, in the backlog, would close part of that gap.

type Peak = object
  peak: string
  m: int
let feetPerMetre = 3.28084
echo peaks.select(
  col.m.mapElements(proc (x: int): int = int(x.float * feetPerMetre)).alias("feet"),
  asStruct(col.peak, col.m).mapElements(proc (p: Peak): string =
    p.peak.split(' ')[^1] & " " & $p.m).alias("label"),
  col.huts.mapElements(proc (h: seq[string]): bool = h.len > 1).alias("several_huts"))
echo peaks.select(fold(lit(0), proc (acc, x: Series): Series = acc + x,
                       col.m, col.m).alias("twice"))
shape: (4, 3)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ feet  ┆ label          ┆ several_huts β”‚
β”‚ ---   ┆ ---            ┆ ---          β”‚
β”‚ i64   ┆ str            ┆ bool         β”‚
β•žβ•β•β•β•β•β•β•β•ͺ════════════════β•ͺ══════════════║
β”‚ 15767 ┆ Blanc 4806     ┆ true         β”‚
β”‚ 15203 ┆ Rosa 4634      ┆ false        β”‚
β”‚ 13323 ┆ Paradiso 4061  ┆ true         β”‚
β”‚ 14783 ┆ Weisshorn 4506 ┆ false        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
shape: (4, 1)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”
β”‚ twice β”‚
β”‚ ---   β”‚
β”‚ i32   β”‚
β•žβ•β•β•β•β•β•β•β•‘
β”‚ 9612  β”‚
β”‚ 9268  β”‚
β”‚ 8122  β”‚
β”‚ 9012  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”˜

9. Smaller functions↑ contents

The 0.4 book ports left a list of Polars functions that Python users reach for, and 0.5 adds them: over(mappingStrategy = MappingStrategy.Explode), shuffle, sample, hash, get, argTrue, upperBound and lowerBound, extendConstant, rle, reshape, name.toLowercase, a meta namespace (outputName, rootNames), equals, vstack, hstack, extend, update, upsample, estimatedSize and collectAll.

Two of them needed a choice:

One more fix came with fold: an operation between a Series of length 1 and a longer one now broadcasts, as it does in Polars.

echo peaks.estimatedSize(SizeUnit.Kilobytes), " kB"
let e = (col.m * 2).alias("double")
echo e.meta.outputName, " from ", e.meta.rootNames
let parts = peaks.explode("countries").partitionBy("countries", asDict = true)
for key, part in parts:
  echo key, ": ", part.height, " rows"
0.224609375 kB
double from @["m"]
@["France"]: 1 rows
@["Italy"]: 3 rows
@["Switzerland"]: 2 rows

What's next↑ contents

0.6 is the "production" release: streaming sinks, cloud storage, Arrow interop, decimals and binary columns (Designing Nanuq 0.6). The 0.5 explainer is Above 4000.

Source files↑ contents

Every source file this page mentions, folded: tap one to read it. A file's name in the text leads here.

benchmarks/map_elements.nim: the Nim side 35 lines
## mapElements benchmark, Nim side: Nanuq mapElements vs native expressions.
##
## Run: nim r -d:release benchmarks/map_elements.nim [n]   (compare with map_elements.py)
import std/[monotimes, times, os, strutils, strformat]
import nanuq

let n = if paramCount() > 0: parseInt(paramStr(1)) else: 1_000_000
var ms = newSeq[int](n)
var peaks = newSeq[string](n)
for i in 0 ..< n:
  ms[i] = 4000 + i mod 900
  peaks[i] = "Peak " & $(i mod 1000)
let df = newDataFrame(series("m", ms), series("peak", peaks))

proc bench(name: string, e: Expr, reps = 3) =
  var best = high(int64)
  for _ in 1 .. reps:
    let t = getMonoTime()
    discard df.select(e)
    best = min(best, (getMonoTime() - t).inNanoseconds)
  echo &"{name:<40} {best.float / 1e6:9.1f} ms"

type Row = object
  peak: string
  m: int

echo &"Nanuq, {n} rows"
bench("int: mapElements(x*3.28084)", col.m.mapElements(proc (x: int): float = x.float * 3.28084))
bench("int: native m*3.28084", col.m * 3.28084)
bench("str: mapElements(len)", col.peak.mapElements(proc (s: string): int = s.len))
bench("str: native str.lenChars", col.peak.str.lenChars)
bench("struct: mapElements(row)", asStruct("peak", "m").mapElements(proc (r: Row): int =
  (if r.peak.endsWith("7"): r.m else: 0)))
bench("struct: native when/then",
      `when`(col.peak.str.endsWith("7")).then(col.m).otherwise(0))

benchmarks/map_elements.nim

benchmarks/map_elements.py: the Python side 30 lines
"""mapElements benchmark, Python side: py-polars map_elements vs native expressions.

Run: python3 benchmarks/map_elements.py [n]   (compare with map_elements.nim)
"""
import sys, time
import polars as pl

n = int(sys.argv[1]) if len(sys.argv) > 1 else 1_000_000
df = pl.DataFrame({
    "m": [4000 + i % 900 for i in range(n)],
    "peak": [f"Peak {i % 1000}" for i in range(n)],
})

def bench(name, expr, reps=3):
    best = float("inf")
    for _ in range(reps):
        t = time.perf_counter()
        df.select(expr)
        best = min(best, time.perf_counter() - t)
    print(f"{name:40s} {best * 1000:9.1f} ms")

print(f"py-polars {pl.__version__}, {n:,} rows")
bench("int: map_elements(x*3.28084)", pl.col.m.map_elements(lambda x: x * 3.28084, return_dtype=pl.Float64))
bench("int: native m*3.28084", pl.col.m * 3.28084)
bench("str: map_elements(len)", pl.col.peak.map_elements(lambda s: len(s), return_dtype=pl.Int64))
bench("str: native str.len_chars", pl.col.peak.str.len_chars())
bench("struct: map_elements(row)", pl.struct("peak", "m").map_elements(
    lambda r: r["m"] if r["peak"].endswith("7") else 0, return_dtype=pl.Int64))
bench("struct: native when/then",
      pl.when(pl.col.peak.str.ends_with("7")).then(pl.col.m).otherwise(0))

benchmarks/map_elements.py