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:
- Table-header names (
list[str]): match the tables, butstruct[2]hides the field names, and it is not what you write. - Python's repr, exactly: matches
df.schemain Python character for character, butArray(Float64, shape=(3,))and single quotes are not Nim. - 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. - Nim types (
seq[string]): lossy, sinceInt32andInt64would both beint.
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:
- Empty lists.
@[]has no element type in Nim. In anewDataFrameblock it takes the type of the other rows, asnildoes for missing values since 0.3. Thehutscolumn above has an empty list in its last row. - Tuples and objects become structs. A named tuple or an object value gives a Struct column. Python uses dicts, which in Nim would lose the field types.
array[N, T]becomes an Array, so the width is known at compile time.
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:
partitionBy(asDict = true)gives a Python dict keyed by tuples. A Nim table needs one key type, so the keys areseq[string]with each value as text; a typed table would need the key types at compile time.hash(seed)takes one seed. Python takes four, but only the first matters for most uses, and Rust Polars takes one.
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