dftk — DataFrame analysis and manipulation toolkit
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 search.
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).
Installation
uv tool install dataframe-toolkit
dftk --help
Or with pip:
pip install dataframe-toolkit
To install the latest main branch directly from GitHub:
uv tool install git+https://github.com/hemingur/dataframe-toolkit.git
To install from a local clone:
git clone https://github.com/hemingur/dataframe-toolkit.git
cd dataframe-toolkit
uv tool install .
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:
dftk skill install # every agent found: ~/.claude and/or ~/.codex
dftk skill install --codex # only one (--claude or --codex; creates the folder)
dftk skill install --dir DIR # another agent's skills folder
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 completion
dftk completion install # for your shell ($SHELL): bash or zsh
dftk completion install --shell zsh
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/share/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.
Quick example
dftk dataset tips | dftk stat - -c tip total_bill -g day
Chain commands with a bare -o (write a temp parquet, print its path)
instead of piping TSV text: the next 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:
dftk dataset tips -o \
| dftk pivot -i day -v tip -f mean -o \
| dftk print
Subcommands
Data transformation
| Command |
Description |
eval |
Add or modify columns: eval expressions, string/path functions, statistical ops |
query |
Filter rows with pandas query expressions or SQL (--sql via DuckDB) |
merge |
Join two tables on key columns (inner/left/right/outer) |
concat |
Concatenate two or more tables row-wise |
append |
Add one row from -c COL=VALUE; --inplace adds it to a file, e.g. a status log |
melt |
Reshape wide-to-long (pd.melt) |
explode |
Split separated values in a cell (a,b) into one row per value |
implode |
Join a column's values within groups into one cell, the inverse of explode |
pivot |
Reshape long-to-wide with per-cell aggregation |
func |
Column transforms: cumsum, group mean/sum/min/max/count/median/std, rank, qcut:N; interpolate/ffill/bfill within groups by an x column |
scale |
Normalise: z-score, min-shift, sum/max/mean scaling, Blom rank, regression residuals |
interp |
Interpolate values from a reference curve into a table (1-D lookup) |
binx |
Assign bin indices to a column based on explicit or generated edges |
transpose |
Flip rows and columns; original column names land in a new --keycol column |
segid |
Assign a segment ID that increments on each value change in a column |
cleannames |
Rename columns to lowercase identifiers (Sample ID → sample_id), e.g. for SQL |
Statistics
| Command |
Description |
stat |
Descriptive statistics (count/mean/std/CI/SEM/skew/kurtosis) with grouping and bootstrap |
wstat |
Weighted descriptive statistics (wmean, wstd, weighted quantile CI) |
fit |
OLS/robust/weighted regression via R-style formulas; tidy table, --summary, --anova |
test |
P-values between column pairs: t-test, Mann-Whitney, Wilcoxon, KS, correlations, bootstrap; groups |
corr |
Pairwise column correlations (Pearson/Spearman/Kendall) with optional BCa bootstrap CI; globs (-c '*:*') or a full matrix (--all) |
describe |
Quick column-level summary (dtype, n, n_unique, n_null, sample values) |
info |
Per-column dtype, null counts, and memory usage; --summary for dataset-level totals |
randvar |
Sample from a distribution and append as a new column (norm, alpha, beta, …) |
Plots
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.
| Command |
Description |
scat |
Scatter plot; OLS/robust or LOWESS fit (--fit lowess, one per group with -g), hexagonal binning for large tables (--hexbin), bubble size (--sizecol), colour (--colorcol), error bars (--xerr/--yerr, --errscale 1.96), weighted fit (--fit -w W) |
line |
Line plot; optional error bars (--yerr) or intervals (--yci lo,hi), -ls none -m o for points only, and fit overlay |
box |
Box or violin plot (--kind violin) of a value by category; -g boxes side by side, --points every point jittered on top, --count n under each category, --order |
hist |
Histogram or KDE (--kde); normalisation, cumulative mode, mean±σ annotation (--stats) |
chi |
Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
heatmap |
Coloured grid of values from a long (-x -y -v) or wide (-y) table; correlograms from corr --all, --annot, --lower; --subgraphcol panels on one colour scale |
pairs |
Scatter-plot matrix with KDEs (or histograms) on the diagonal; -g colours groups, --upper corr puts r in the upper triangle |
qq |
QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; -g one curve and λ per group |
forest |
Forest plot: one row per estimate with its interval (--se or --ci lo,hi), --exp for odds/hazard ratios on a log axis, --text/--textcol numbers on the right, -g several series per row, --section headers |
phewas |
PheWAS plot: -log10(p) of each phenotype grouped by category (one colour each), ▲/▼ by the sign of --betacol, Bonferroni line, hits labelled; --subgraphcol stacks one panel per model or gene |
locus |
Regional association plot: -log10(p) in one region coloured by r² with the lead variant (--ldcol), lead as a diamond, --lead/--label by ID or chr:pos |
manhattan |
Genome-wide -log10(p) by position (Chr, pos, Pval, or --mlogpcol/--chi2col); significance lines, thinning for millions of variants, -g/--subgraphcol for several scans |
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.
Utilities
| Command |
Description |
dataset |
Load a curated example dataset from dftk, seaborn, statsmodels, or pydataset |
sample |
Random row sampling (with or without replacement, by count or fraction) |
split |
Split a dataframe into one file per group |
annotate |
Read and write provenance metadata (genome, source, …) in parquet files |
print |
Read any dftk input (TSV, parquet, stdin) and write TSV, JSON, Markdown or LaTeX |
clean |
Remove leftover temp parquet pipe files from interrupted pipelines |
completion |
Tab completion for bash and zsh: dftk completion install |
help |
List all subcommands or show full help for one: dftk help stat |
Common patterns
Chaining commands
# z-score sepal_length within species, then fit against petal_length
dftk dataset iris -o \
| dftk scale -c sepal_length -g species -o \
| dftk fit -f "sepal_length_scaled ~ petal_length" -g species
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):
dftk dataset fertility -o \
| dftk cleannames -o \
| dftk query --sql "SELECT country_name, x1960, x2000 FROM data LIMIT 3"
For your own export, dftk cleannames data.tsv --backend duckdb -o data.parquet also keeps integer columns with empty cells as integers.
JSON files
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:
printf '%s\n' '{"id": 1, "pos": {"chr": "1", "start": 100}, "tags": ["x", "y"]}' \
'{"id": 2, "pos": {"chr": "2", "start": 200}, "tags": []}' \
> records.jsonl
dftk query --sql \
"SELECT * EXCLUDE (pos, tags), pos.*, len(tags) AS ntags FROM 'records.jsonl'"
# id chr start ntags
# 1 1 100 2
# 2 2 200 0
dftk query --sql "SELECT id, unnest(tags) AS tag FROM 'records.jsonl'" -o \
| dftk pivot -i tag -v id -f count
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: