Skip to content
F231d4aa57a40bb2163ef00dfcd06b129c2c78ca

F231d4aa57a40bb2163ef00dfcd06b129c2c78ca

github.com • November 28, 2026

dftk is a command-line toolkit for exploratory data analysis on TSV files. Each subcommand reads tabular data, performs one operation, and writes TSV to stdout, making it easy to chain commands in pipelines.

dftk was developed during computational genomics research as a fast, composable alternative to writing one-off pandas scripts. It is designed for analysts who live in the terminal and want a consistent, pipeable toolkit for the full data analysis pipeline — from initial exploration through statistical modelling and publication-quality figures.

No data file handy? Every example below uses dftk dataset to pull in a small, real dataset, so you can copy-paste any of them and run them right now. Run dftk dataset --list to browse everything available (dozens of datasets from seaborn, statsmodels, and pydataset, plus gwas , a synthetic association scan, and phewas , a synthetic phenome-wide scan, both made by dftk). dftk dataset NAME searches dftk, seaborn, statsmodels and pydataset in that order and returns the first match, so --source is optional — pass it only to disambiguate a name that exists in more than one source, or to restrict the .

Cheatsheet: two landscape pages with the commands, options, SQL idioms, plots and pipeline recipes at a glance — dftk-cheatsheet.pdf . Every example on it is run against dftk when it is built ( python docs/cheatsheet/make_cheatsheet.py ).

To install the latest main branch directly from GitHub:

To install from a local clone:

Skill for coding agents

dftk ships an agent skill: a short guide that coding agents such as Codex and Claude Code load when a task involves dftk. It covers the piping conventions, which command to use for what, and patterns for Snakemake and Make. Install it with:

It prints where it installed the skill. Run it again after upgrading dftk so the skill matches the installed version; it replaces only the earlier dftk skill. The source is in src/dftk/skills/dftk/ .

Tab then completes commands, options, the values an option allows ( --format , --fit , --catwidth , …) and file names. The script is plain shell generated from dftk's own parsers, so pressing Tab is instant.

bash: installed to ~/.local/ /bash-completion/completions/dftk , which bash-completion loads by itself (most Linux systems load it in ~/.bashrc ; on macOS, brew install bash-completion@2 ). Open a new shell.

zsh: installed to ~/.zfunc/_dftk . Add fpath+=~/.zfunc to ~/.zshrc before compinit (with Oh My Zsh, before the line that sources oh-my-zsh.sh ), then open a new shell; if it doesn't complete, rm ~/.zcompdump* once.

Run it again after upgrading dftk so new options complete; dftk skill install also refreshes an installed completion script. dftk completion print writes the script to stdout instead.

Chain commands with a bare -o (write a temp parquet, print its path) instead of piping TSV text: the command sees the path on stdin and reads that file. It's faster for large data, keeps column types exact, and is the recommended pattern once a pipeline has more than one step:

All plot commands write a PNG/PDF when -f FILE is given, or display interactively otherwise. They support --groupcol for colour grouping, --subgraphcol for subplot grids, and figure/font presets for publication-quality output.

scat , line and hist draw dashed reference lines with --vline X and --hline Y , each labelled when written X:LABEL ( --vline 412:carriers ); forest takes --vline and box --hline . scat and line also draw sloped lines y = A + B*x with --abline A:B[:LABEL] (intercept, then slope, as in R; --abline 0:0.15:15% ), across the whole panel without changing its limits; a bare --abline is the identity line y = x, and a negative intercept is written --abline=-1:2 . On log axes the line is drawn as the curve it is. With --subgraphcol the same lines go on every panel.

Clean up spreadsheet headers

Headers such as Country Name or 1960 need quoting in SQL. cleannames turns them into lowercase identifiers ( country_name , x1960 ) and keeps the original names in the parquet metadata ( dftk annotate FILE ):

For your own export, dftk cleannames data.tsv --backend duckdb -o data.parquet also keeps integer columns with empty cells as integers.

DuckDB reads JSON itself, so query --sql takes a JSON file in FROM (a file of records, [{...}, {...}] , or JSON Lines, one object per line; 'logs/*.jsonl' reads several). When the SQL doesn't use the data table, dftk reads no input. In TSV a nested object or list is shown as one line of JSON ( ["x","y"] ), which later commands can't compute on, so flatten it in the same query: pos.* makes a column of each field, len() counts a list and unnest() gives one row per item:

A field that is a string in some records and a list in others (a variant catalog's ReferenceRegion , say) gets DuckDB type JSON; TSV shows its strings without quotes and its lists as JSON. json_type() tells them apart, so a list can become one row per item:

dftk reads JSON as a table, and a table has every column in every row: a record without a key gets an empty cell, and JSON output ( -o FILE.json , .jsonl , --format json ; see Output formats ) writes that cell as null . So dftk is the tool for getting a table out of JSON, not for filtering JSON and keeping it JSON. With a third record {"locus": "ATXN8"} in catalog.jsonl :

jq filters records without making a table, so each comes out as it went in, and can also write TSV for a dftk pipeline:

JSON output is for tables: results, small records ( append , below), input for tools that want JSON. Nested values and mixed fields are written as JSON again.

One row: status logs and small records

append adds one row from -c COL=VALUE values; columns not given stay empty. Numbers and true / false are typed, a quoted value ( '"007"' ) stays text and note= is empty. Without input it makes a one-row table, a quick way to write a small JSON record:

--inplace adds the row to a file, creating it if missing: a status log that parallel jobs (Snakemake rules, array jobs) can write to, since the file's directory is locked while each row is written. --timestamp adds the local time as ISO 8601 text ( 2026-11-09T19:13:57 , no space, so awk and cut see one field; a real timestamp in .parquet ), and --strict refuses columns the log doesn't have, so a typo can't start a new one:

A row whose columns are all in a TSV header, and any .jsonl row, is written as one more line; existing rows are never changed. A new column, or a .parquet log, rewrites the file (to a temp file that then replaces it). In a .jsonl log records need not keys; read it back with dftk query --sql "SELECT * FROM 'runs.jsonl'" .

Large tables: hexbin instead of points

With tens of thousands of points a scatter plot is a solid blob. --hexbin counts points per hexagon instead ( --hexlog for a log colour scale), and --fit lowess adds a smooth curve:

--colorcol COL colours each hexagon by the mean of COL instead of the count; with --subgraphcol all panels one colour scale.

Group summary then plot

Wide-to-long then plot overlaid histograms

Interpolation (standard curve lookup)

Filling missing values

eval -f takes pandas column methods ( COL.method(...) ); fillna , ffill , bfill and interpolate fill empty cells and keep the others.

Write to a new column ( x_filled = x.fillna(y) ) to keep the original, and mark the gaps first ( missing = x.isna() ) to tell filled values apart. Only empty cells are filled: a missing row (a year with no row at all) is not added.

Defaults from another table. A column that is in both files gets the suffix _r from merge ; fill from it, then drop it. Here the defaults are each species' median body mass:

From neighbouring rows ( co2 is a weekly series with gaps):

ffill leaves the first rows empty and bfill the last ones; x.ffill().fillna(x.bfill()) fills both. interpolate() counts one step per row, so the rows must be evenly spaced; for unevenly spaced rows use func -t interpolate --xcol X (below), and for a lookup from a reference curve, dftk interp .

Row order and groups. These methods use the rows in the order they are in. Sort first, in a step of its own: --sortasc applies to a command's output, so in the same command it would come after the fill. When a table holds several series (sites, countries, samples), fill within each group, or values are taken from the neighbouring group. Rows of a group don't need to be to each other, but within each group they must be in order:

For interpolation within groups, func -t interpolate does it in one step. It draws the line against an x column ( --xcol , required), so unevenly spaced rows (missing years, genome positions) get the right values; it takes each group's rows in X order itself, so no sort step is needed, and it leaves gaps before a group's first value or after its last empty. -t ffill and -t bfill work the same way; chained after interpolate on the same column ( -d ), they fill those ends too:

eval 's interpolate() counts one step per row: with 10 at x=2 and 14 at x=6, it gives the gap at x=5 12.0, where func --xcol gives 13.0.

Differences between rows

For the change in a column from one row to the , eval -f takes pandas diff() and pct_change() , also within groups. They use the rows in their order, so sort first, in a step of its own:

The first row of each country gets an empty cell. Without groupby(Country) , it would be compared with the last row of the country.

To compare a value with one in another column of the or row, for example the gap between segments given by Chr , Begin , End , use SQL's LAG() / LEAD() in query --sql :

A negative gap is an overlap, and the first segment on each chromosome gets an empty cell. lead("Begin") OVER (...) - "End" gives the gap to the segment instead.

Begin and End are SQL keywords: quote such column names with double quotes and the whole statement with single quotes.

No sorting is needed first; ORDER BY inside OVER sets the order.

Integers stay integers.

eval -f can do the same with pandas shift , but it goes by row order, so sort by Chr and Begin first (results are floats):

Without groupby(Chr) the first segment of a chromosome is compared with the last one of the chromosome.

Correlograms and heatmaps

corr --all correlates every pair of numeric columns both ways round, plus the diagonal, which is the square table heatmap draws. Values of both signs get diverging colours centred on 0; --vmin -1 --vmax 1 keeps the full scale for r, so a weak correlation doesn't look strong. --annot writes the values in the cells and --lower keeps the lower triangle:

Missing values are dropped pair by pair, so nobs can differ between cells; dftk print --dropna -o | dftk corr --all uses the complete rows throughout. p-values are not adjusted for multiple testing.

For the shape of each relationship, not just r, pairs draws every pair of columns as a scatter plot with each column's KDE on the diagonal; -g colours groups (each group's KDE scaled by its of the rows) and --upper corr writes r in the upper triangle, with -g also r within each group, which can differ even in sign from r over all rows:

heatmap draws any table with one row per cell ( -x -y -v ), or a wide one with -y naming the row labels and the other numeric columns as heatmap columns, as pivot makes it:

--subgraphcol draws one heatmap per value of a column, side by side. Every panel has the same rows, columns and colour scale, with one colour bar, so a colour means the same value in every panel:

manhattan draws -log10(p) of every variant along the genome, chromosomes end to end in order (1–22, X, Y, MT; a chr prefix is ignored). The columns are Chr , pos and Pval unless named with --chrcol , --poscol and --pcol ; a missing default is looked for under common spellings ( CHR , #CHROM , BP , P , …). dataset gwas is a synthetic scan to try it on:

A p-value below 1e-308 is stored as 0, which plots as -log10(p) = 323 with a warning. A chi-squared column gives the true value however small p is ( --chi2df , default 1, a number or a column), and --mlogpcol takes a column that already holds -log10(p), such as regenie's LOG10P :

Points with p > 0.01 are thinned to one per cell of a grid finer than the figure ( --no-thin draws all), and points are rasterized: ten million variants take a few seconds and a PDF stays small. --ylim LO HI caps the axis, with points above it drawn as triangles on the top edge. --logy instead keeps every peak: the axis is linear up to -log10(p) = 10 and logarithmic above it ( --logy 5 moves the switch), so a peak at 380 and one at 8 both show. --sigcolor red colours the points past the --sig line.

Several scans in one table: --subgraphcol study draws a panel each, -g study a colour each, and --miami study draws two of them face to face (a Miami plot): the first on top, the second upside down below it, with the chromosome numbers between them. The column must hold two values, or name the two to draw ( --miami study a b , top first). Here the second scan is the example one with every chi-squared halved:

qq plots the same p-values (same column options, no chromosome or position needed) against what null tests would give, with a 95 % band ( --ci ) and the genomic inflation factor λ, the median chi-squared over its null median. A curve lifted off the diagonal from the start, λ above 1.05, points to stratification or other inflation; a few points leaving it at the top are associations. With -g , each group gets its own curve and λ:

qq --logy makes its y axis linear up to 10 and logarithmic above, as in manhattan .

locus zooms in on one region: -log10(p) against position in Mb, the points coloured by r² with the lead variant ( --ldcol , five bins, grey where missing) and the lead drawn as a diamond. It plots the rows it gets, so cut the region out with query first (input on several chromosomes is an error that suggests a query around the top hit). The lead is the smallest p-value unless --lead names one, and --label names more variants to write on the plot; both take an ID ( SNP column, or --idcol ) or a position like chr6:32600000 . dftk doesn't compute LD: merge in r² with the lead, e.g. from plink --r2 --ld-snp . dataset gwas has an r2 column around each peak:

phewas draws a phenome-wide scan: -log10(p) of each phenotype, the phenotypes grouped by category along the x axis in one colour per category (columns category , phenotype and Pval unless named with -c , -l and the p-value options of manhattan ). With --betacol beta the points are triangles pointing up or down with the sign of the effect. The significance line is Bonferroni (0.05 / number of tests) unless --sig gives a p-value, and the phenotypes above it are labelled, at most --label N (default 10). --labelpercat 1 labels only the strongest hit of each category, and --labelnumbers writes numbers instead of names, left to right, with the key on stdout for a caption. Every category is as wide on the x axis ( --catwidth count makes a category as wide as its number of phenotypes). One row per phenotype: pick one genotype or mask with query first, or draw one panel each with --subgraphcol .

--subgraphcol COL stacks one PheWAS per value of a column: burden models of one gene, genes within one model, or genotypes. A phenotype stands at the same x in every panel and the panels one y axis. The Bonferroni line counts each panel's own tests; --sig P draws one line at P in all of them:

forest draws one row per estimate: a point with its interval, labels down the left, top to bottom in file order (sort first to order them), and a reference line at 0. Give the interval as two columns ( --ci lo,hi ) or a standard error ( --se se , ± 1.96 SE, --level to change). --exp turns log odds ratios (or any log-scale estimate) into ratios on a log axis with the reference at 1; --text writes estimate [lo, hi] to the right and --textcol adds columns such as the p-value or the number of carriers. -g puts several series on each row (het and hom carriers, two cohorts), --section groups rows under bold headers, --weighted sizes the markers by 1/SE². Coefficients from fit :

dataset phewas is a simulated phenome-wide scan of loss-of-function carriers (heterozygous and homozygous rows per phenotype, log odds ratios, five real effects) to try it on:

Bootstrap confidence intervals

Bootstrap mode repeats the full stat computation N times on resampled data and emits one row per resample (

A TSV filename as a positional argument

A .parquet filename to read a named parquet file directly

Nothing, or - , to read stdin: either TSV, or the parquet path printed by a command's bare -o (that temp file is then read and deleted)

A pipe as the filename, e.g. ) escaped; it needs \usepackage{booktabs} , and goes inside your own table environment with \input{tips_by_day.tex} . Add \usepackage[T1]{fontenc} (pdfLaTeX's default font has no straight " , which JSON lists contain):

lines and preambles

dftk has no or skip-rows option: # is ordinary data, so headers like Count # and values like A #1 are read as they are. Drop lines or a preamble in the shell instead:

With --backend duckdb , a whole-line # below the header is an error, and # lines above the header are skipped.

Files without a header

--noheader reads the first line as data and names the columns V1 , V2 , …. It only describes the input: the output gets a header ( V1 V2 … ) unless you add --removeheader . Name the columns with --move :

In merge , --noheader applies to both files, so both sides are named V1 V2 … . The key appears once and the right side's other columns get the _r suffix. --move runs after the merge, so it renames the merged names:

Parquet always has column names, so --removeheader with -o and --noheader on parquet input do nothing (dftk warns).

Standard output options (available on all tabular commands):

-o / --output — controls where output goes; takes an optional value: -o alone — write a temp parquet to pipe into the command, printing its path to stdout (auto-deleted once read) -o FILE.parquet — write a named, reusable parquet, printing its path to stdout -o FILE (no .parquet extension) — write TSV to FILE , with no stdout output omit -o entirely — write TSV to stdout (the default)

-o alone — write a temp parquet to pipe into the command, printing its path to stdout (auto-deleted once read)

-o FILE.parquet — write a named, reusable parquet, printing its path to stdout

-o FILE (no .parquet extension) — write TSV to FILE , with no stdout output

omit -o entirely — write TSV to stdout (the default)

--select col1 col2 … — keep only these columns

--drop col1 col2 … — remove these columns

--round N — round numeric output

--postquery EXPR — filter output rows after processing

--move OLD:NEW … — rename columns

--removeheader — leave out the header row in TSV output

--meta KEY=VALUE — embed provenance metadata in parquet output (repeatable)

Provenance annotations

Metadata embedded with --meta is stored in the parquet file schema and propagates automatically through the pipe: every subsequent -o write re-embeds it alongside any new --meta values.

Figure options (plot commands)

pandas , numpy , scipy — core data handling and statistics

statsmodels — regression ( fit , scale --resid , wstat )

duckdb — SQL queries ( query --sql )

matplotlib , seaborn — plots

pyarrow — parquet I/O backend