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.
use std::{env, fs, process};
let csv = "day,station,temp,rain
1,north,12.5,3.0
1,south,18.0,0.0
1,east,15.0,0.5
2,north,13.5,1.5
2,south,19.5,0.0
2,east,14.0,2.0
3,north,11.0,
3,south,17.5,4.5
3,east,15.5,0.0
4,north,12.0,6.0
4,south,20.5,0.0
4,east,16.0,1.0
";
let path = env::temp_dir() / f"weather_{process::id()}.csv";
try fs::write(path, csv);
let t = try table::read_csv(path.as_str());
println(t.shape());
println(t.head(4));
try fs::remove_file(path);
(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.
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()}");
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.
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);
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.
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")]));
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.
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}");
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.
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}");
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.
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
arrowArrow IPC: the file format (.arrow, Feather v2) and the streaming format, read and written without an Arrow library.buildBuilding tables: thetable!literal, records of a struct (#[derive(Record)], orRecordby hand), cells from Nabi values.columnTyped column storage: one packedListper column plus an optional validity bitmap.csvCSV (RFC 4180) through thecsvpackage: 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.dateCalendar dates and timestamps in the proleptic Gregorian calendar, UTC, with no leap seconds.displayText forms of a table: the aligned previewDisplayprints (rows and columns cut in the middle past a limit) and GitHub-flavoured Markdown.errorThe one error type.exprColumn 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.frameThe table: named, ordered columns of one length, and the operations that only reshape rows or columns (selection, slicing, nulls).groupGroup-by and aggregation.joinHash joins.jsonlJSON lines: one JSON object per line, a row each.lazyLazy queries: aQueryrecords the operations of a table pipeline as a plan and runs it only oncollect, 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).opsRelational algebra as operators: the join symbols of Codd's algebra (⋈ ⟕ ⟖ ⟗ ⋉ ▷), the set operators (∪ ∩from core,∖here) and indexing by column name.parquetParquet files, read and written without a Parquet library.reshapeLong <-> wide:pivotspreads one column's values into columns,meltstacks columns into (variable, value) rows.schemaColumn types and the schema of a table.sortSorting: 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.statsSummaries:describe,value_counts,null_counts.valueOne 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}ArrowHow to read or write Arrow IPC data.arrow_schemaThe schema of the Arrow data inb, without reading its rows.read_arrowThe Arrow file (or stream) atpath:Arrow::new().read_file(path).write_arrowWritettopathin the Arrow file format.
build::{Record, ToValue, record_table}Source
pub use build::{Record, ToValue, record_table}RecordA struct whose values are rows:#[derive(table::Record)]writes it from the fields (each aToValuetype), or implement it by hand.ToValueA Nabi value that is one cell.record_tableA 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::ColumnColumnOne typed column.
pkg::csv::{Csv, CsvReader, read_csv, read_csv_str, write_csv}Source
pub use pkg::csv::{Csv, CsvReader, read_csv, read_csv_str, write_csv}CsvHow to read or write CSV.CsvReaderReads CSV from a stream in batches.read_csvRead the CSV file atpathwith the default options.read_csv_strA table from CSV text with the default options.write_csvWrite the table as CSV topathwith the default options.
date::{Date, DateTime}Source
pub use date::{Date, DateTime}error::TableErrorSource
pub use error::TableErrorTableErrorWhat went wrong in a table operation.
expr::{Expr, IntoExpr, Then, When, col, lit, when}Source
pub use expr::{Expr, IntoExpr, Then, When, col, lit, when}ExprA computed column: names columns withcol, scalars withlit(or a plain number, string, bool or date on either side of an operator), and combines them with the dot operators.IntoExprWhat can stand on either side of an expression operator: anExpr, a number, string, bool, date orValue.ThenAwhen(..).then(..)waiting for itsotherwise.WhenAwhen(..)waiting for itsthen.colColumnnameof the table the expression runs against.litA scalar, the same in every row.whenthenwherecondistrue, elseotherwise; start withwhen.
frame::{Row, Table}Source
pub use frame::{Row, Table}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}AggOne aggregation: a kind, its input column and the output name (<column>_<kind>unlessnamed).AggKindWhat an aggregation computes.GroupByA table split into groups by key columns, ready to aggregate.countRows per group, namedcount.count_ofNon-null values ofcper group.customfof each group's slice of columnc, namedname.firstThe first non-null value.lastThe last non-null value.maxLargest value, any orderable type.meanArithmetic mean, compensated sum over the count.medianThe 0.5 quantile, linear interpolation.minSmallest value, any orderable type.n_uniqueHow many distinct non-null values.quantileTheqquantile (0 <= q <= 1), linear interpolation.stdSample standard deviation, Welford's one-pass update.sumSum (i64staysi64;f64with Neumaier compensation).varSample variance (n - 1), Welford.
join::HowSource
pub use join::HowHowWhich 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_jsonlThe JSON lines file atpathas a table.read_jsonl_strA table from JSON lines text; blank lines are skipped.write_jsonlWrite the table as JSON lines topath.write_jsonl_strThe 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}LazyGroupByA query grouped by key columns, waiting for its aggregations.QueryA table pipeline that runs oncollect.scan_arrowArrow::new().scan(path).scan_csvCsv::new().scan(path).scan_parquetParquet::new().scan(path).
parquet::{Compression, Parquet, parquet_schema, read_parquet, write_parquet}Source
pub use parquet::{Compression, Parquet, parquet_schema, read_parquet, write_parquet}CompressionThe page compression a written file uses.ParquetHow to read or write Parquet.parquet_schemaThe schema of the Parquet data inb(its readable columns), from the footer alone.read_parquetThe Parquet file atpath:Parquet::new().read_file(path).write_parquetWritettopathas Parquet with the defaults ofParquet::new().
schema::{DType, Field, Schema}Source
pub use schema::{DType, Field, Schema}sort::{SortKey, asc, desc}Source
pub use sort::{SortKey, asc, desc}value::ValueSource
pub use value::ValueValueA single cell.