packages

table

Column-oriented tables. A Table is named, ordered Columns of one length; each column is one typed List (i64, f64, bool, str, dictionary-encoded str, date, datetime) plus a validity bitmap for nulls. Operations run a column at a time; grouping and joins hash rows into integer keys first (keys), so no per-row allocation.

#Tutorial: a first data analysis

This tutorial takes a small data set from a CSV file to numbers and a plot: read it with table, clean it, group and summarize it, test a difference with stats, and draw it with plot. Each step is a complete script; run any of them with nabi run file.nabi.

table, stats and plot are official packages, so a script can use them without nabi add: the first nabi run adds each one it finds and says so (Added table ^0.1 (official)).

#Read a CSV file

The data: daily readings from three weather stations over a week. table::read_csv reads a file and works out each column's type from its values; table::read_csv_str does the same for text already in memory. Here the script writes the file first, so it runs anywhere.

text
(12, 4)
shape: (4, 4)
day | station | temp | rain
i64 | str     | f64  | f64
----+---------+------+-----
  1 | north   | 12.5 |  3.0
  1 | south   | 18.0 |  0.0
  1 | east    | 15.0 |  0.5
  2 | north   | 13.5 |  1.5

The header row names the columns, and each column has one type: day holds integers, station text, temp and rain floating-point numbers. The empty rain on day 3 is a null, a value that is not there; tables keep nulls instead of turning them into zero or NaN.

#Clean it

Nulls have to go somewhere before a mean or a test. fill_null puts a value in their place; drop_nulls removes the rows that have one. Which is right depends on the data: a missing rain gauge reading is not "no rain", so this script drops the row, and shows the count either way.

nabi
let t = try table::read_csv_str("day,station,temp,rain
1,north,12.5,3.0
2,north,13.5,1.5
3,north,11.0,
4,north,12.0,6.0
");
let rain = try t.column("rain");
println(f"{rain.null_count()} null of {t.nrows()}");

let dropped = try t.drop_nulls(["rain"]);
let filled = try t.fill_null("rain", table::Value::Float);
println(f"dropped: {dropped.nrows()} rows; filled: {try filled.column("rain").to_f64()}");
text
1 null of 4
dropped: 3 rows; filled: [3.0, 1.5, 0.0, 6.0]

#Add columns and filter rows

Column expressions use the same dot operators as arrays (.+, .*, .> ..): col("temp") .* 1.8 .+ 32.0 is a new column computed from temp, row by row. filter keeps the rows where a condition holds.

nabi
use table::col;

let t = table::table!{
    "station": ["north", "south", "east", "north", "south", "east"],
    "temp":    [12.5, 18.0, 15.0, 13.5, 19.5, 14.0],
    "rain":    [3.0, 0.0, 0.5, 1.5, 0.0, 2.0],
};
let t = try t.with_column("temp_f", col("temp") .* 1.8 .+ 32.0);
let wet = try t.filter(col("rain") .> 1.0);
println(wet);
text
shape: (3, 4)
station | temp | rain | temp_f
str     | f64  | f64  | f64
--------+------+------+-------
north   | 12.5 |  3.0 |   54.5
north   | 13.5 |  1.5 |   56.3
east    | 14.0 |  2.0 |   57.2

#Group and summarize

group_by collects the rows of each station; agg computes one value per group for each expression it is given. Aggregates are named after their column (temp_mean), and .named renames one.

nabi
use table::{desc, max, mean, sum};

let t = table::table!{
    "station": ["north", "south", "east", "north", "south", "east", "north", "south", "east"],
    "temp":    [12.5, 18.0, 15.0, 13.5, 19.5, 14.0, 11.0, 17.5, 15.5],
    "rain":    [3.0, 0.0, 0.5, 1.5, 0.0, 2.0, 0.5, 4.5, 0.0],
};
let by = try (try t.group_by(["station"])).agg([mean("temp"), max("temp"), sum("rain").named("total_rain")]);
println(try by.sort([desc("temp_mean")]));
text
shape: (3, 4)
station | temp_mean | temp_max | total_rain
str     | f64       | f64      | f64
--------+-----------+----------+-----------
south   | 18.333333 |     19.5 |        4.5
east    | 14.833333 |     15.5 |        2.5
north   | 12.333333 |     13.5 |        5.0

#Statistics on a column

A column becomes a Vector<f64> with to_f64, and from there every stats function applies. stats::describe gives the usual summary at once.

nabi
let t = table::table!{
    "station": ["north", "south", "north", "south", "north", "south", "north", "south"],
    "temp":    [12.5, 18.0, 13.5, 19.5, 11.0, 17.5, 12.0, 20.5],
};
let temp = try t.column("temp").to_f64();
println(f"mean {stats::mean(temp):.2}, std {stats::std(temp, ddof: 1):.2}, median {stats::median(temp)}");

let s = stats::describe(temp);
println(f"n {s.n}, min {s.min}, q1 {s.q1}, q3 {s.q3}, max {s.max}");
text
mean 15.56, std 3.72, median 15.5
n 8, min 11, q1 12.375, q3 18.375, max 20.5

ddof: 1 asks for the sample standard deviation, dividing by n - 1; without it std divides by n, as NumPy does.

#Is the difference real?

The south station looks warmer. A two-sample t-test asks whether a difference that large is likely if the two stations had the same mean. stats::ttest_ind runs Welch's test, which does not assume equal variances; the result has the statistic, the p-value and a confidence interval for the difference.

nabi
use table::col;

let t = table::table!{
    "station": ["north", "south", "north", "south", "north", "south", "north", "south"],
    "temp":    [12.5, 18.0, 13.5, 19.5, 11.0, 17.5, 12.0, 20.5],
};
let north = try (try t.filter(col("station") .== "north")).column("temp").to_f64();
let south = try (try t.filter(col("station") .== "south")).column("temp").to_f64();

let r = try stats::ttest_ind(south, north);
println(f"t = {r.statistic:.2}, p = {r.pvalue:.5}");
println(f"south is warmer by {r.estimate:.2} C, 95% interval {r.ci}");
text
t = 7.68, p = 0.00036
south is warmer by 6.62 C, 95% interval [4.474617987003727, 8.775382012996273]

A p-value this small says that two stations with equal means would rarely give samples this far apart. With four readings each, the interval is still wide: more data narrows it.

#Plot it

plot builds a figure from layers with method calls, and writes SVG, PNG or text for the terminal (ax.term()). scatter and line take the same vectors the statistics did; label names a layer for the legend. save picks the format from the file name.

nabi
let day = [1.0, 2.0, 3.0, 4.0];
let north = [12.5, 13.5, 11.0, 12.0];
let south = [18.0, 19.5, 17.5, 20.5];

let ax = plot::axes()
    .line(day, north).label("north").marker(plot::Marker::Circle)
    .line(day, south).label("south").marker(plot::Marker::Circle)
    .xlabel("day").ylabel("temperature [C]")
    .title("Daily temperature");
try ax.save("weather.svg");

With its table feature, plot draws a table's columns by name (plot::frame); its docs show every kind of figure.

In a Jupyter notebook (nabi jupyter), a cell whose last value is a plot shows the SVG under the cell, so there is no file to write.

#What next

  • Linear algebra, dense and sparse solves systems and fits least squares.
  • Statistics goes further: distributions, more tests, regression.
  • The modules below list joins, pivots, windows, Parquet and lazy queries.

Modules

  • arrow Arrow IPC: the file format (.arrow, Feather v2) and the streaming format, read and written without an Arrow library.
  • build Building tables: the table! literal, records of a struct (#[derive(Record)], or Record by hand), cells from Nabi values.
  • column Typed column storage: one packed List per column plus an optional validity bitmap.
  • csv CSV (RFC 4180) through the csv package: a header line, any one-byte delimiter, "-quoted fields with "" for a quote and line breaks inside, LF / CRLF / CR line ends, a UTF-8 BOM skipped.
  • date Calendar dates and timestamps in the proleptic Gregorian calendar, UTC, with no leap seconds.
  • display Text forms of a table: the aligned preview Display prints (rows and columns cut in the middle past a limit) and GitHub-flavoured Markdown.
  • error The one error type.
  • expr Column expressions: a small tree built with the dot operators (col("x") .* 2 .+ col("y"), col("a") .> 3 .&& col("b") .== "k") and evaluated column at a time against a table.
  • frame The table: named, ordered columns of one length, and the operations that only reshape rows or columns (selection, slicing, nulls).
  • group Group-by and aggregation.
  • join Hash joins.
  • jsonl JSON lines: one JSON object per line, a row each.
  • lazy Lazy queries: a Query records the operations of a table pipeline as a plan and runs it only on collect, after an optimizer has moved filters as early as they can go (into a file scan, where Parquet row groups whose statistics rule a filter out are not read) and pruned every column nothing downstream uses (a scan reads only those).
  • ops Relational algebra as operators: the join symbols of Codd's algebra (⋈ ⟕ ⟖ ⟗ ⋉ ▷), the set operators (∪ ∩ from core, ∖ here) and indexing by column name.
  • parquet Parquet files, read and written without a Parquet library.
  • reshape Long <-> wide: pivot spreads one column's values into columns, melt stacks columns into (variable, value) rows.
  • schema Column types and the schema of a table.
  • sort Sorting: every key becomes an order-preserving u64 per row (numbers by their bits, strings by rank among the distinct values), then a stable LSD radix sort of (key, row) pairs, last key first.
  • stats Summaries: describe, value_counts, null_counts.
  • value One cell, the element type of rows and the scalar of expressions.

Re-exports

arrow::{Arrow, arrow_schema, read_arrow, write_arrow}Source

pub use arrow::{Arrow, arrow_schema, read_arrow, write_arrow}
  • Arrow How to read or write Arrow IPC data.
  • arrow_schema The schema of the Arrow data in b, without reading its rows.
  • read_arrow The Arrow file (or stream) at path: Arrow::new().read_file(path).
  • write_arrow Write t to path in the Arrow file format.

build::{Record, ToValue, record_table}Source

pub use build::{Record, ToValue, record_table}
  • Record A struct whose values are rows: #[derive(table::Record)] writes it from the fields (each a ToValue type), or implement it by hand.
  • ToValue A Nabi value that is one cell.
  • record_table A table with one row per record; the column types come from the struct, so an empty list still has the columns.

column::ColumnSource

pub use column::Column

csv::{Csv, CsvReader, read_csv, read_csv_str, write_csv}Source

pub use csv::{Csv, CsvReader, read_csv, read_csv_str, write_csv}
  • Csv How to read or write CSV.
  • CsvReader Reads CSV from a stream in batches.
  • read_csv Read the CSV file at path with the default options.
  • read_csv_str A table from CSV text with the default options.
  • write_csv Write the table as CSV to path with the default options.

date::{Date, DateTime}Source

pub use date::{Date, DateTime}
  • Date A calendar date: days since 1970-01-01 (negative before it).
  • DateTime An instant: nanoseconds since 1970-01-01T00:00:00Z, which covers the years 1677 to 2262.

error::TableErrorSource

pub use error::TableError

expr::{Expr, IntoExpr, Then, When, col, lit, when}Source

pub use expr::{Expr, IntoExpr, Then, When, col, lit, when}
  • Expr A computed column: names columns with col, scalars with lit (or a plain number, string, bool or date on either side of an operator), and combines them with the dot operators.
  • IntoExpr What can stand on either side of an expression operator: an Expr, a number, string, bool, date or Value.
  • Then A when(..).then(..) waiting for its otherwise.
  • When A when(..) waiting for its then.
  • col Column name of the table the expression runs against.
  • lit A scalar, the same in every row.
  • when then where cond is true, else otherwise; start with when.

frame::{Row, Table}Source

pub use frame::{Row, Table}
  • Row One row of a table, read by column name.
  • Table Named, ordered columns of equal length.

group::{Agg, AggKind, GroupBy, count, count_of, custom, first, last, max, mean, median, min, n_unique, quantile, std, sum, var}Source

pub use group::{Agg, AggKind, GroupBy, count, count_of, custom, first, last, max, mean, median, min, n_unique, quantile, std, sum, var}
  • Agg One aggregation: a kind, its input column and the output name (<column>_<kind> unless named).
  • AggKind What an aggregation computes.
  • GroupBy A table split into groups by key columns, ready to aggregate.
  • count Rows per group, named count.
  • count_of Non-null values of c per group.
  • custom f of each group's slice of column c, named name.
  • first The first non-null value.
  • last The last non-null value.
  • max Largest value, any orderable type.
  • mean Arithmetic mean, compensated sum over the count.
  • median The 0.5 quantile, linear interpolation.
  • min Smallest value, any orderable type.
  • n_unique How many distinct non-null values.
  • quantile The q quantile (0 <= q <= 1), linear interpolation.
  • std Sample standard deviation, Welford's one-pass update.
  • sum Sum (i64 stays i64; f64 with Neumaier compensation).
  • var Sample variance (n - 1), Welford.

join::HowSource

pub use join::How
  • How Which rows a join keeps.

jsonl::{read_jsonl, read_jsonl_str, write_jsonl, write_jsonl_str}Source

pub use jsonl::{read_jsonl, read_jsonl_str, write_jsonl, write_jsonl_str}
  • read_jsonl The JSON lines file at path as a table.
  • read_jsonl_str A table from JSON lines text; blank lines are skipped.
  • write_jsonl Write the table as JSON lines to path.
  • write_jsonl_str The table as JSON lines, one object per row, each line ended by \n.

lazy::{LazyGroupBy, Query, scan_arrow, scan_csv, scan_parquet}Source

pub use lazy::{LazyGroupBy, Query, scan_arrow, scan_csv, scan_parquet}

parquet::{Compression, Parquet, parquet_schema, read_parquet, write_parquet}Source

pub use parquet::{Compression, Parquet, parquet_schema, read_parquet, write_parquet}
  • Compression The page compression a written file uses.
  • Parquet How to read or write Parquet.
  • parquet_schema The schema of the Parquet data in b (its readable columns), from the footer alone.
  • read_parquet The Parquet file at path: Parquet::new().read_file(path).
  • write_parquet Write t to path as Parquet with the defaults of Parquet::new().

schema::{DType, Field, Schema}Source

pub use schema::{DType, Field, Schema}
  • DType The type of a column.
  • Field A column's name and type.
  • Schema The names and types of a table's columns, in order.

sort::{SortKey, asc, desc}Source

pub use sort::{SortKey, asc, desc}
  • SortKey One sort key: a column, its direction and where nulls go.
  • asc Ascending by name, nulls last.
  • desc Descending by name, nulls last.

value::ValueSource

pub use value::Value