Skip to content

Aggregation and Statistics

Joel Natividad edited this page Nov 30, 2026 · 29 revisions

Aggregation & Statistics

Tier: Intermediate Commands covered: stats, moarstats, frequency, pragmastat, dedup, extdedup, extsort

Note

Per-command flag reference lives in /docs/help/. This page is the workflow layer — when to reach for each command and how they compose.

These commands turn raw rows into numbers. The headline feature is stats — 48 metrics in under a second on 2.7M rows. The runner-up is frequency — multithreaded with an index, Apache DataSketches-backed frequent_items mode for huge cardinalities.

Quick decision table

If you want to… Use Notes
Compute mean/median/stddev/etc. with guaranteed type inference stats 48 metrics; sub-second on millions of rows
Add bivariate, robust, and outlier stats to an existing stats CSV moarstats 73 additional measures
See the top-N values per column (and how often each occurs) frequency Apache DataSketches mode for huge cardinalities
Robust median-of-pairwise stats (Hodges-Lehmann, Shamos) pragmastat Date/datetime aware via stats cache
Drop duplicate rows dedup Streaming with --sorted, in-memory otherwise
Drop duplicates from a file > RAM extdedup On-disk hash table; preserves input order
Sort a file > RAM extsort Multithreaded external merge sort

stats

The headline command. Computes up to 48 summary statistics with guaranteed data type inference (Null / String / Float / Integer / Date / DateTime / Boolean). Streaming by default; loads into memory for non-streaming stats like median / quartiles / cardinality. Multithreaded with an index.

A successful run writes a <filename>.stats.csv cache file that many other commands reuse (frequency, schema, pragmastat, pivotp, sqlp scoresql, etc.) — see Stats Cache & Caching.

(30.0.0: dathere/qsv#5104.) --quote <char>, --escape <char> and --no-quoting read CSV with non-standard quoting, as in validate. With any of them set, stats uses no index, so it doesn't split the file across cores and is slower on big files. A stats cache made with one quoting isn't reused with another. JSONL and Parquet inputs ignore these options.

Example: full profile of NYC 311 with date and boolean inference

qsv stats --everything --infer-dates --infer-boolean \
  NYC_311_SR_2010-2020-sample-1M.csv > nyc311-stats.csv

--everything adds cardinality, modes/antimodes, median, MAD, quartiles, IQR, fences, skewness, percentiles, and zero_padded_numeric (flags String columns that are entirely zero-padded numbers — zip codes, barcodes, padded IDs — so they aren't mistakenly loaded as integer/float downstream). --infer-dates recognizes 19 date formats; --infer-boolean detects 2-valued patterns like t/f, yes/no, 1/0.

The zero_padded_numeric column can also be enabled on its own with --zero-padded-numeric:

qsv stats --zero-padded-numeric data.csv

Example: pre-populate the stats cache to speed up downstream commands

# Run this once; every smart command (frequency, schema, pragmastat, pivotp, ...)
# will pick up the cache automatically.
qsv stats --cardinality --stats-jsonl NYC_311_SR_2010-2020-sample-1M.csv
ls NYC_311_SR_2010-2020-sample-1M.{stats.csv,stats.csv.data.jsonl}

Example: get the stats as JSON on stdout

stats writes CSV by default. --jsonl emits the same per-column stats as JSON Lines (one object per column) on stdout, and --pretty-json emits them as a single pretty-printed JSON array — handy for piping into jq or an LLM without touching the sidecar files.

# NDJSON on stdout — one object per column
qsv stats --everything --jsonl data.csv | jq 'select(.type == "Integer") | .field'

# a single pretty-printed JSON array
qsv stats --pretty-json data.csv -o stats.json

This is the same per-column shape the --stats-jsonl sidecar uses; the difference is where it goes. --jsonl and --pretty-json are mutually exclusive, and neither can be combined with --stats-jsonl.

Example: custom percentiles for a population study

qsv stats --quartiles --percentiles --percentile-list '5,10,25,50,75,90,95' \
  wcp.csv > wcp-percentiles.csv

The deciles and quintiles keywords expand to 10,20,30,...,90 and 20,40,60,80.

Example: weighted stats (e.g., revenue-weighted price)

qsv stats --weight 'Quantity' --quartiles \
  transactions.csv > price-weighted-by-volume.stats.csv

Example: approximate quantiles & cardinality on a 100M-row file

qsv stats --everything \
  --quantile-method approx \
  --cardinality-method approx \
  --mode-cardinality-cap 10000 \
  huge.csv

approx uses Apache DataSketches (t-digest for quantiles, HyperLogLog for cardinality) — constant memory per column, ~1 % rank error. Use this when exact memory blows up.

Note

Under --everything (or --mode), --cardinality-method approx alone does not save memory — --mode-cardinality-cap does. Modes need the exact table of every distinct value, so stats keeps that table whenever modes are computed, and the cardinality comes from it. The cap is what bounds the table: a column that passes it drops its table and reports *HIGH_CARDINALITY for its modes. Under approx, such a column gets a HyperLogLog estimate for its cardinality; under exact, it reports >=<cap>. Without modes (--cardinality alone), approx never builds the table at all.

When a column's exact table survives, its exact count is reported and no sketch is built (#4806). Estimates are capped at the row count, so an all-unique column never reports more distinct values than rows.

Important

Automatic on OOM. When stats estimates that the file is likely bigger than available RAM, it auto-enables --quantile-method approx and --cardinality-method approx and prints a warning listing what got switched on. Pass --quantile-method exact / --cardinality-method exact to force the precise calculation regardless. The stats cache key includes the chosen mode, so switching between exact and approximate runs won't return stale results. Requires a little-endian target (Intel, AMD, Apple Silicon, ARM — everything except IBM s390x, which gets a clear error).

The automatic switch to approx cardinality gives no memory relief when modes are computed (--everything, --mode): the exact table of distinct values is kept for the modes either way. Add --mode-cardinality-cap for that (see the note above).

NaN cells

Note

NaN, nan and NAN cells — how pandas and numpy write missing values — are skipped by every numeric statistic, in stats and in moarstats, which runs stats (#5053).

What stats does with a NaN cell:

  • Every numeric statistic skips it: sum, mean, exact median, quartiles, IQR, MAD, fences, skewness, percentiles, and the weighted mean and standard deviation under --weight. The statistics are those of the column's other values.
  • It still counts as a value, not a null: nullcount and sparsity don't count it, cardinality does, and the column stays Float. A column of integers plus one NaN is therefore summarized as floats, so its min and max read 1.0, not 1, and its sum is not exact past 2^53.
  • A column of only NaN cells has no sum, as it has no mean (#5056).
  • min, max, range, sort_order and sortiness skip it too — 30.0.0 (#5137). In 29.0.0 a NaN in the first row pinned min and max at NaN (NaN,1,2 reported min=NaN max=NaN, and schema then wrote no minimum/maximum), and a column of only NaN cells reported NaN, NaN and Unsorted. Those statistics are now empty for such a column, like an all-null column.
  • max_precision ignores NaN and inf cells (#5050).
  • inf / -inf cells are otherwise treated as values.

After upgrading you don't need --force: stats recomputes a cache written by another qsv version on its next use (the cache records the qsv version; see Stats Cache & Caching). The per-statistic rules are in docs/STATS_DEFINITIONS.md.

See also: /docs/help/stats.md, docs/STATS_DEFINITIONS.md — definitions of every metric, moarstats, Stats Cache & Caching.

moarstats

Adds up to 73 more measures — univariate (Pearson's second skewness, IQR-to-range ratio, Z-scores of min/max/mode, quartile coefficient of dispersion, …), outlier, and --bivariate pair statistics — plus W3C XSD datatype mapping to an existing .stats.csv. Multithreaded with an index.

moarstats looks for <FILESTEM>.stats.csv and runs stats first if it doesn't exist.

Worked example of these measures as data-quality checks: Recipe: Data-Quality Signals with moarstats.

Example: extend allegheny property sales stats

# moarstats updates the stats CSV in place — use -o to write a separate file instead
qsv moarstats allegheny_property_sales.csv -o allegheny.moarstats.csv

Example: build the cache first, then add moar stats

qsv stats --everything --stats-jsonl allegheny_property_sales.csv
qsv moarstats allegheny_property_sales.csv

Feeds viz smart: running moarstats before viz smart lets the auto-dashboard annotate box panels with skew direction and outlier share. Bimodal columns render as histograms instead of box plots either way: plain viz smart computes the bimodality coefficient itself, identically to moarstats --advanced (see Visualization).

Note

Measures at a glance:

  • From the stats cache, no extra pass: mad_normalized (MAD/0.6745) and iqr_normalized (IQR/1.349) — robust, normal-consistent estimates of sigma; robust_min_zscore/robust_max_zscore (Iglewicz-Hoaglin modified z-scores of the extremes); kelly_skewness and percentile_ratio_90_10 (from P10/P90); zero_share, which flags zero-inflation; and berger_parker_dominance, the mode's share of rows (any field type).
  • --advanced: moment_skewness (G1); the L-moment ratios l_cv, l_skewness and l_kurtosis — bounded, outlier-resistant analogues of CV, skewness and kurtosis; lag1_autocorrelation in file order, which exposes trends, drift and clustered blocks; hoover_index; and benford_mad, Nigrini's first-digit conformity test as a data-quality / fabrication signal (only emitted for numeric data with ≥ 100 non-zero values spanning at least two orders of magnitude).
  • --bivariate: cramersv (Cramér's V, for any pair of field types) and regression (regression_slope, regression_intercept, r_squared of field2 on field1). Both are in --bivariate-stats all.
  • jarque_bera, bimodality_coefficient and kurtosis match scipy (#4651).
  • Upgrades recompute automatically: a .stats.csv whose sidecar was written by another qsv version is treated as stale, so the appended columns are recomputed (#4655).
  • Repeated header names each get their own statistics (#4663).

Example: winsorize and trim at the 10th/90th percentiles

qsv moarstats allegheny_property_sales.csv --use-percentiles --pct-thresholds 10,90
# adds winsorized_mean_10pct, trimmed_mean_10pct, … (default pair: 5,95)

By default the winsorized and trimmed measures cut at Q1/Q3. --use-percentiles cuts at a percentile pair instead, and --pct-thresholds chooses the pair. You don't need to request those percentiles from stats yourself. qsv adds the pair to the --percentile-list of its stats run, and a stats CSV whose percentile list lacks them is recomputed. Both values must be whole percentiles from 1 to 100, with the lower one first.

Example: bivariate pair statistics

qsv moarstats allegheny_property_sales.csv --bivariate -S pearson,spearman,cramersv,regression
# writes allegheny_property_sales.stats.bivariate.csv:
# field1,field2,pearson_correlation,spearman_correlation,cramers_v,regression_slope,regression_intercept,r_squared,n_pairs

How --bivariate picks its pairs:

  • All-unique numeric columns are included (#4654) — typical for prices, coordinates and durations at full precision. Their correlation, covariance and regression are reported, with only the frequency statistics (mutual information, Theil's U, Cramér's V) left empty.
  • String columns are not correlated (#4656). Pearson/Spearman/Kendall/covariance/regression use only Integer, Float, Date, DateTime and Boolean columns; a String column still takes part in the frequency statistics.
  • The sidecar is always rewritten — header-only when no pair qualifies — so a stale one from an earlier run can't pass for this run's result.

See also: /docs/help/moarstats.md, stats, pragmastat — the robust-stats counterpart, Visualization — charting with viz.

frequency

Frequency distribution tables per column. Output as CSV (default), JSON, or TOON (compact LLM-friendly format). Multithreaded with an index. The stats cache gives a big speedup on ID-like (all-unique) columns.

For columns with millions of unique values, use --sketch-method frequent_items (Apache DataSketches Misra-Gries) — bounded memory, top-K with bounded error.

Example: top-10 NYC 311 complaint types

qsv frequency --select 'Complaint Type' --limit 10 NYC_311_SR_2010-2020-sample-1M.csv
field,value,count,percentage,rank
Complaint Type,Noise - Residential,71872,7.19,1
Complaint Type,HEATING,67234,6.72,2
Complaint Type,GENERAL CONSTRUCTION,52111,5.21,3
...
Complaint Type,Other,538295,53.83,0

Example: build a fresh-cached frequency table for downstream consumers

qsv index NYC_311_SR_2010-2020-sample-1M.csv
qsv stats --cardinality --stats-jsonl NYC_311_SR_2010-2020-sample-1M.csv
qsv frequency --frequency-jsonl NYC_311_SR_2010-2020-sample-1M.csv
ls NYC_311_SR_2010-2020-sample-1M.freq.csv.data.jsonl

Example: top-100 cities by frequency, JSON output for an LLM prompt

qsv frequency --select AccentCity --limit 100 --asc wcp.csv > top_cities.csv
qsv frequency --select AccentCity --limit 100 --asc --json wcp.csv > top_cities.json
qsv frequency --select AccentCity --limit 100 --asc --toon wcp.csv > top_cities.toon

Example: heavy-hitter detection on a huge cardinality column

qsv frequency --select 'Session ID' \
  --sketch-method frequent_items \
  --sketch-map-size 16384 \
  --limit 50 events.csv > hot_sessions.csv

Important

Automatic on OOM. frequency auto-enables --sketch-method frequent_items (Misra-Gries) when the file is likely bigger than RAM and prints a warning. Pass --sketch-method exact to force exact frequencies regardless. Note that frequent_items tracks heavy hitters only — --asc, --ignore-case, --no-trim, --frequency-jsonl, --json, and weighted frequencies are incompatible and require exact. Requires a little-endian target.

NULLs under frequent_items are exact. NULLs are counted outside the sketch and laid out as in exact mode: last, after "Other", with no percentage or rank (or ranked by their exact count under --pct-nulls). They don't take a --limit slot or end up in "Other". Only the values' counts and "Other" are estimates.

--ignore-case and the <ALL_UNIQUE> shortcut. The stats cache's cardinality is case-sensitive, so it can't show that Bob@x.com and bob@x.com are the same value. Under -i, all-unique columns are therefore counted in full instead of being collapsed to <ALL_UNIQUE>, except Integer columns, which have no letters to fold. On large files that costs memory proportional to the row count for each such text column (emails, names); leave out the ones you don't need with --select.

Whitespace and the <ALL_UNIQUE> shortcut. The stats cache counts untrimmed values, and frequency trims by default, so a and a are distinct to the stats cache but one value to frequency. While skipping an all-unique column, frequency checks whether trimming changes any of its values; if one does, it recounts that column in full and names it in a message, instead of printing a misleading <ALL_UNIQUE> row. Clean ID columns keep the shortcut, and --no-trim (nothing is trimmed) is unaffected.

Example: filter columns dynamically with a Luau expression on stats

# Skip floats and columns with > 1,000 nulls
qsv frequency --stats-filter "type == 'Float' or nullcount > 1000" data.csv

--stats-filter requires the luau feature and the stats cache.

Note

  • --lmt-threshold applies its limits only to columns with at least that many unique values.
  • --other-sorted works the same in CSV and JSON output.
  • frequency (and stats) accept --flexible for ragged CSVs — see Troubleshooting.

See also: /docs/help/frequency.md, stats (pre-populate the cache for speed), Stats Cache & Caching.

pragmastat

Robust statistics from the Pragmastat library — designed for heavy-tailed, outlier-prone data where mean and stddev mislead. Computes Hodges-Lehmann center (median of pairwise averages) and Shamos spread (median of pairwise absolute differences), each with confidence bounds. Both estimators tolerate up to 29 % corruption.

By default, pragmastat appends 7 ps_* columns to the existing stats cache.

Note

ps_* columns are matched to their columns exactly (#4665), including repeated header names and --no-headers input. A reused cache that can't be matched unambiguously leaves the ps_* cells empty with a warning; delete the cache (--force recomputes only the ps_* columns, never the baseline) to regenerate it.

Example: robust spread for Allegheny property sales (highly skewed)

qsv stats -E --infer-dates --stats-jsonl allegheny_property_sales.csv
qsv pragmastat --select 'Sale Price' allegheny_property_sales.csv

The --standalone flag emits standalone CSV instead of appending to the cache.

Example: two-sample comparison — does Borough A differ from Borough B?

qsv pragmastat --twosample --select 'priceA,priceB' market_split.csv

Example: confirmatory test — is median latency below 100 ms?

qsv pragmastat --compare1 'center:100' --select latency_ms requests.csv

See also: /docs/help/pragmastat.md, Pragmastat library, stats, moarstats.

dedup

Drop duplicate rows. By default it sorts in memory then deduplicates — use --sorted to stream when input is already sorted (constant memory). With -D <file> it writes the duplicates to a separate file for audit.

Example: deduplicate Boston 311 by composite key

qsv dedup --select 'Created Date,Incident Address' boston311-100.csv > unique.csv

Example: sort then stream-dedup a contact list

qsv sort --select Email contacts.csv \
  | qsv dedup --select Email --sorted -D dupes.csv > unique.csv

Example: case-insensitive dedup of email addresses

qsv dedup --select Email --ignore-case contacts.csv > unique.csv

For files larger than RAM use extdedup.

See also: /docs/help/dedup.md, sort, sortcheck, extdedup.

extdedup

Memory-mapped, on-disk hash table dedup for arbitrarily large files. Unlike dedup, it preserves input order. Two modes: CSV (with --select) and line-by-line (any text file).

Example: dedup a 50 GB clickstream by session_id without loading it into memory

qsv extdedup --select session_id huge_clickstream.csv > unique.csv

Example: line-mode dedup on a log file

qsv extdedup --no-headers nginx-access.log > unique-lines.log

See also: /docs/help/extdedup.md, extsort, Recipe: Larger-than-RAM CSV.

extsort

Multithreaded external merge sort for files larger than RAM. Two modes: CSV (with --select, requires an index) and line-mode (any text file).

Example: sort a 16 GB NYC 311 export by Created Date for time-series joins

qsv index nyc311-full.csv
qsv extsort --select 'Created Date' nyc311-full.csv > nyc311-by-date.csv

Example: sort a 100 GB log file alphabetically (line mode)

qsv extsort --no-headers huge-log.txt > sorted-log.txt

After extsort, follow up with dedup --sorted for streaming dedup, or joinp asof for time-series joins.

See also: /docs/help/extsort.md, sort, dedup --sorted, Recipe: Larger-than-RAM CSV.

Whitespace markers

Both stats and frequency accept --vis-whitespace, which replaces whitespace characters in the output (e.g. min/max/mode/antimode and frequency values) with visible markers, so leading, trailing, and embedded whitespace is easy to spot. Spaces are only marked when a value is entirely spaces — a value of three spaces becomes 《_》《_》《_》, while embedded single spaces in mixed text are left as-is.

Character Unicode Marker
space (only when the whole value is spaces) U+0020 《_》
tab U+0009 《→》
newline U+000A 《¶》
carriage return U+000D 《⏎》
vertical tab U+000B 《⋮》
form feed U+000C 《␌》
next line U+0085 《␤》
left-to-right mark U+200E 《␎》
right-to-left mark U+200F 《␏》
line separator U+2028 《␊》
paragraph separator U+2029 《␍》
non-breaking space U+00A0 《⍽》
em space U+2003 《emsp》
figure space U+2007 《figsp》
zero-width space U+200B 《zwsp》

The first three follow Rust's whitespace reference; the rest cover other common invisible characters. The canonical mapping is WHITESPACE_MARKERS in src/util.rs.

See also

Home · Why qsv? · Tier legend

Quick links

Get Started

Command Reference

Cookbook

Tuning & Internals

Ecosystem

Reference

Legacy

Clone this wiki locally