dataframe-toolkit 0.15.1__tar.gz → 0.17.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/PKG-INFO +53 -2
  2. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/README.md +52 -1
  3. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/__init__.py +3 -0
  6. dataframe_toolkit-0.17.0/src/dftk/commands/append_cmd.py +424 -0
  7. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/corr_cmd.py +169 -23
  8. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/eval_cmd.py +12 -6
  9. dataframe_toolkit-0.17.0/src/dftk/commands/heatmap_cmd.py +253 -0
  10. dataframe_toolkit-0.17.0/src/dftk/commands/pairs_cmd.py +366 -0
  11. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/skills/dftk/SKILL.md +14 -3
  12. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/__init__.py +0 -0
  13. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/cli.py +0 -0
  14. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/annotate_cmd.py +0 -0
  15. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/base.py +0 -0
  16. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/binx_cmd.py +0 -0
  17. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/chi_cmd.py +0 -0
  18. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/clean_cmd.py +0 -0
  19. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  20. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/concat_cmd.py +0 -0
  21. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/dataset_cmd.py +0 -0
  22. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/describe_cmd.py +0 -0
  23. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/explode_cmd.py +0 -0
  24. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/fit_cmd.py +0 -0
  25. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/func_cmd.py +0 -0
  26. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/help.py +0 -0
  27. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/hist_cmd.py +0 -0
  28. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/implode_cmd.py +0 -0
  29. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/info_cmd.py +0 -0
  30. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/interp_cmd.py +0 -0
  31. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/line_cmd.py +0 -0
  32. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/melt_cmd.py +0 -0
  33. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/merge_cmd.py +0 -0
  34. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/pivot_cmd.py +0 -0
  35. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/print_cmd.py +0 -0
  36. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/query_cmd.py +0 -0
  37. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/randvar_cmd.py +0 -0
  38. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/sample_cmd.py +0 -0
  39. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/scale_cmd.py +0 -0
  40. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/scat_cmd.py +0 -0
  41. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/segid_cmd.py +0 -0
  42. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/skill_cmd.py +0 -0
  43. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/split_cmd.py +0 -0
  44. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/stat_cmd.py +0 -0
  45. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/test_cmd.py +0 -0
  46. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/transpose_cmd.py +0 -0
  47. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/commands/wstat_cmd.py +0 -0
  48. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/common/__init__.py +0 -0
  49. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/common/copula.py +0 -0
  50. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/common/docformats.py +0 -0
  51. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/common/evalfuncs.py +0 -0
  52. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/common/io.py +0 -0
  53. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/common/plot.py +0 -0
  54. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/common/seed.py +0 -0
  55. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/common/seq.py +0 -0
  56. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/common/stats.py +0 -0
  57. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/io.py +0 -0
  58. {dataframe_toolkit-0.15.1 → dataframe_toolkit-0.17.0}/src/dftk/skills/dftk/references/snakemake.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: dataframe-toolkit
3
- Version: 0.15.1
3
+ Version: 0.17.0
4
4
  Summary: A command-line toolkit for DataFrame analysis and manipulation
5
5
  Keywords: dataframe,statistics,data analysis,CLI,TSV,pandas
6
6
  Author: Gunnar Pálsson
@@ -119,6 +119,7 @@ dftk dataset tips -o \
119
119
  | `query` | Filter rows with pandas query expressions or SQL (`--sql` via DuckDB) |
120
120
  | `merge` | Join two tables on key columns (inner/left/right/outer) |
121
121
  | `concat` | Concatenate two or more tables row-wise |
122
+ | `append` | Add one row from `-c COL=VALUE`; `--inplace` adds it to a file, e.g. a status log |
122
123
  | `melt` | Reshape wide-to-long (`pd.melt`) |
123
124
  | `explode` | Split separated values in a cell (`a,b`) into one row per value |
124
125
  | `implode` | Join a column's values within groups into one cell, the inverse of `explode` |
@@ -139,7 +140,7 @@ dftk dataset tips -o \
139
140
  | `wstat` | Weighted descriptive statistics (wmean, wstd, weighted quantile CI) |
140
141
  | `fit` | OLS/robust/weighted regression via R-style formulas; tidy table, `--summary`, `--anova` |
141
142
  | `test` | P-values between column pairs: t-test, Mann-Whitney, Wilcoxon, KS, correlations, bootstrap; groups |
142
- | `corr` | Pairwise column correlations (Pearson/Spearman/Kendall) with optional BCa bootstrap CI |
143
+ | `corr` | Pairwise column correlations (Pearson/Spearman/Kendall) with optional BCa bootstrap CI; globs (`-c '*:*'`) or a full matrix (`--all`) |
143
144
  | `describe` | Quick column-level summary (dtype, n, n_unique, n_null, sample values) |
144
145
  | `info` | Per-column dtype, null counts, and memory usage; `--summary` for dataset-level totals |
145
146
  | `randvar` | Sample from a distribution and append as a new column (norm, alpha, beta, …) |
@@ -157,6 +158,8 @@ publication-quality output.
157
158
  | `line` | Line plot; optional error bars (`--yerr`) or CI bands (`--yci lo,hi`) and fit overlay |
158
159
  | `hist` | Histogram or KDE (`--kde`); normalisation, cumulative mode, mean±σ annotation (`--stats`) |
159
160
  | `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
161
+ | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
162
+ | `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
160
163
 
161
164
  ### Utilities
162
165
 
@@ -236,6 +239,26 @@ dftk query --sql "SELECT * FROM 'catalog.jsonl' WHERE locus LIKE 'ATXN%'" --form
236
239
  # ]
237
240
  ```
238
241
 
242
+ ### One row: status logs and small records
243
+
244
+ `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:
245
+
246
+ ```bash
247
+ dftk append -c sample=S12 -c reads=48213 -c ok=true --format json
248
+ # [
249
+ # {"sample": "S12", "reads": 48213, "ok": true}
250
+ # ]
251
+ ```
252
+
253
+ `--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:
254
+
255
+ ```bash
256
+ dftk append runs.tsv --inplace -c step=align -c sample=S12 -c status=ok --timestamp
257
+ dftk append runs.jsonl --inplace -c step=align -c reads=48213 --timestamp
258
+ ```
259
+
260
+ 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 share keys; read it back with `dftk query --sql "SELECT * FROM 'runs.jsonl'"`.
261
+
239
262
  ### Large tables: hexbin instead of points
240
263
 
241
264
  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:
@@ -409,6 +432,34 @@ dftk eval segments.tsv -f 'gap = Begin - End.groupby(Chr).shift()'
409
432
  Without `groupby(Chr)` the first segment of a chromosome is compared with
410
433
  the last one of the previous chromosome.
411
434
 
435
+ ### Correlograms and heatmaps
436
+
437
+ `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:
438
+
439
+ ```bash
440
+ dftk dataset iris -o | dftk corr --all -o \
441
+ | dftk heatmap -x col1 -y col2 -v correlation --annot --vmin -1 --vmax 1 -f iris_corr.png
442
+ dftk dataset diamonds -o | dftk corr --all --method spearman -o \
443
+ | dftk heatmap -x col1 -y col2 -v correlation --annot --lower --square \
444
+ --vmin -1 --vmax 1 -f diamonds_corr.png
445
+ ```
446
+
447
+ 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.
448
+
449
+ 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 share 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:
450
+
451
+ ```bash
452
+ dftk dataset iris -o | dftk pairs -g species -f iris_pairs.png
453
+ dftk dataset iris -o | dftk pairs -g species --upper corr --diag hist -f iris_pairs_r.png
454
+ ```
455
+
456
+ `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:
457
+
458
+ ```bash
459
+ dftk dataset penguins -o | dftk pivot -i species -g island -v body_mass_g -f count -o \
460
+ | dftk heatmap -y species --annot --cmap Blues -f penguin_counts.png
461
+ ```
462
+
412
463
  ### Bootstrap confidence intervals
413
464
 
414
465
  Bootstrap mode repeats the full stat computation N times on resampled data
@@ -89,6 +89,7 @@ dftk dataset tips -o \
89
89
  | `query` | Filter rows with pandas query expressions or SQL (`--sql` via DuckDB) |
90
90
  | `merge` | Join two tables on key columns (inner/left/right/outer) |
91
91
  | `concat` | Concatenate two or more tables row-wise |
92
+ | `append` | Add one row from `-c COL=VALUE`; `--inplace` adds it to a file, e.g. a status log |
92
93
  | `melt` | Reshape wide-to-long (`pd.melt`) |
93
94
  | `explode` | Split separated values in a cell (`a,b`) into one row per value |
94
95
  | `implode` | Join a column's values within groups into one cell, the inverse of `explode` |
@@ -109,7 +110,7 @@ dftk dataset tips -o \
109
110
  | `wstat` | Weighted descriptive statistics (wmean, wstd, weighted quantile CI) |
110
111
  | `fit` | OLS/robust/weighted regression via R-style formulas; tidy table, `--summary`, `--anova` |
111
112
  | `test` | P-values between column pairs: t-test, Mann-Whitney, Wilcoxon, KS, correlations, bootstrap; groups |
112
- | `corr` | Pairwise column correlations (Pearson/Spearman/Kendall) with optional BCa bootstrap CI |
113
+ | `corr` | Pairwise column correlations (Pearson/Spearman/Kendall) with optional BCa bootstrap CI; globs (`-c '*:*'`) or a full matrix (`--all`) |
113
114
  | `describe` | Quick column-level summary (dtype, n, n_unique, n_null, sample values) |
114
115
  | `info` | Per-column dtype, null counts, and memory usage; `--summary` for dataset-level totals |
115
116
  | `randvar` | Sample from a distribution and append as a new column (norm, alpha, beta, …) |
@@ -127,6 +128,8 @@ publication-quality output.
127
128
  | `line` | Line plot; optional error bars (`--yerr`) or CI bands (`--yci lo,hi`) and fit overlay |
128
129
  | `hist` | Histogram or KDE (`--kde`); normalisation, cumulative mode, mean±σ annotation (`--stats`) |
129
130
  | `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
131
+ | `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
132
+ | `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
130
133
 
131
134
  ### Utilities
132
135
 
@@ -206,6 +209,26 @@ dftk query --sql "SELECT * FROM 'catalog.jsonl' WHERE locus LIKE 'ATXN%'" --form
206
209
  # ]
207
210
  ```
208
211
 
212
+ ### One row: status logs and small records
213
+
214
+ `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:
215
+
216
+ ```bash
217
+ dftk append -c sample=S12 -c reads=48213 -c ok=true --format json
218
+ # [
219
+ # {"sample": "S12", "reads": 48213, "ok": true}
220
+ # ]
221
+ ```
222
+
223
+ `--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:
224
+
225
+ ```bash
226
+ dftk append runs.tsv --inplace -c step=align -c sample=S12 -c status=ok --timestamp
227
+ dftk append runs.jsonl --inplace -c step=align -c reads=48213 --timestamp
228
+ ```
229
+
230
+ 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 share keys; read it back with `dftk query --sql "SELECT * FROM 'runs.jsonl'"`.
231
+
209
232
  ### Large tables: hexbin instead of points
210
233
 
211
234
  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:
@@ -379,6 +402,34 @@ dftk eval segments.tsv -f 'gap = Begin - End.groupby(Chr).shift()'
379
402
  Without `groupby(Chr)` the first segment of a chromosome is compared with
380
403
  the last one of the previous chromosome.
381
404
 
405
+ ### Correlograms and heatmaps
406
+
407
+ `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:
408
+
409
+ ```bash
410
+ dftk dataset iris -o | dftk corr --all -o \
411
+ | dftk heatmap -x col1 -y col2 -v correlation --annot --vmin -1 --vmax 1 -f iris_corr.png
412
+ dftk dataset diamonds -o | dftk corr --all --method spearman -o \
413
+ | dftk heatmap -x col1 -y col2 -v correlation --annot --lower --square \
414
+ --vmin -1 --vmax 1 -f diamonds_corr.png
415
+ ```
416
+
417
+ 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.
418
+
419
+ 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 share 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:
420
+
421
+ ```bash
422
+ dftk dataset iris -o | dftk pairs -g species -f iris_pairs.png
423
+ dftk dataset iris -o | dftk pairs -g species --upper corr --diag hist -f iris_pairs_r.png
424
+ ```
425
+
426
+ `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:
427
+
428
+ ```bash
429
+ dftk dataset penguins -o | dftk pivot -i species -g island -v body_mass_g -f count -o \
430
+ | dftk heatmap -y species --annot --cmap Blues -f penguin_counts.png
431
+ ```
432
+
382
433
  ### Bootstrap confidence intervals
383
434
 
384
435
  Bootstrap mode repeats the full stat computation N times on resampled data
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dataframe-toolkit"
3
- version = "0.15.1"
3
+ version = "0.17.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  keywords = [
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dataframe-toolkit"
3
- version = "0.15.1"
3
+ version = "0.17.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -29,6 +29,7 @@ COMMAND_GROUPS: list[tuple[str, list[tuple[str, str]]]] = [
29
29
  ("query", "query_cmd:QueryCommand"),
30
30
  ("merge", "merge_cmd:MergeCommand"),
31
31
  ("concat", "concat_cmd:ConcatCommand"),
32
+ ("append", "append_cmd:AppendCommand"),
32
33
  ("melt", "melt_cmd:MeltCommand"),
33
34
  ("explode", "explode_cmd:ExplodeCommand"),
34
35
  ("implode", "implode_cmd:ImplodeCommand"),
@@ -62,6 +63,8 @@ COMMAND_GROUPS: list[tuple[str, list[tuple[str, str]]]] = [
62
63
  ("line", "line_cmd:LineCommand"),
63
64
  ("hist", "hist_cmd:HistCommand"),
64
65
  ("chi", "chi_cmd:ChiCommand"),
66
+ ("heatmap", "heatmap_cmd:HeatmapCommand"),
67
+ ("pairs", "pairs_cmd:PairsCommand"),
65
68
  ],
66
69
  ),
67
70
  (
@@ -0,0 +1,424 @@
1
+ """
2
+ dftk.commands.append_cmd — dftk append subcommand.
3
+
4
+ Add one row to a table, with values from -c COL=VALUE; columns not given are
5
+ empty (or --fill). Without input it makes a one-row table. --inplace adds
6
+ the row to a file, creating it if missing: a status log that parallel jobs
7
+ can write to, since the file's directory is locked while it is written.
8
+
9
+ In place, a TSV row whose columns are all in the header, and any JSON Lines
10
+ row, is added as one line at the end of the file. A new column, or a
11
+ parquet file, means the file is read and rewritten (to a temp file that then
12
+ replaces it, so an interrupted run leaves the old file).
13
+ """
14
+
15
+ import argparse
16
+ import contextlib
17
+ import csv
18
+ import io as _io
19
+ import json
20
+ import logging
21
+ import os
22
+ import re
23
+ import shutil
24
+ import sys
25
+ import tempfile
26
+
27
+ import pandas as pd
28
+
29
+ from dftk.commands.base import BaseCommand
30
+ from dftk.common import docformats
31
+ from dftk.common.io import _read_parquet_meta, _write_parquet, _write_tsv, io
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+ _INT = re.compile(r"[+-]?\d+")
36
+ _FLOAT = re.compile(r"[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?")
37
+
38
+ # Options that still apply with --inplace; any other read or output option
39
+ # given with it is an error (--prequery would drop rows from the file)
40
+ _INPLACE_OPTIONS = {"DATAFILE", "backend", "digits"}
41
+
42
+
43
+ def parse_value(text: str):
44
+ """A -c value: number, true/false, "quoted text", or text; '' is missing."""
45
+ if text == "":
46
+ return None
47
+ if len(text) >= 2 and text[0] == text[-1] and text[0] in "\"'":
48
+ return text[1:-1]
49
+ if text.lower() in ("true", "false"):
50
+ return text.lower() == "true"
51
+ if _INT.fullmatch(text):
52
+ return int(text)
53
+ if _FLOAT.fullmatch(text):
54
+ return float(text)
55
+ return text
56
+
57
+
58
+ def _row(args: argparse.Namespace) -> tuple[dict, dict]:
59
+ """The new row as {column: value}, and the text each value was given as."""
60
+ values: dict = {}
61
+ texts: dict = {}
62
+ for item in args.constant:
63
+ col, sep, text = item.partition("=")
64
+ col, text = col.strip(), text.strip()
65
+ if not sep or not col:
66
+ raise ValueError(f"-c expects COL=VALUE, got {item!r}")
67
+ values[col] = parse_value(text)
68
+ texts[col] = text
69
+ if args.timestamp is not None:
70
+ # ISO 8601 text, no space: one field for awk and cut; read back as
71
+ # a datetime by dftk, DuckDB and pandas
72
+ now = pd.Timestamp.now().floor("s").isoformat()
73
+ values[args.timestamp] = now
74
+ texts[args.timestamp] = now
75
+ if not values:
76
+ raise ValueError("nothing to append: give -c COL=VALUE or --timestamp")
77
+ return values, texts
78
+
79
+
80
+ def _is_text(series: pd.Series) -> bool:
81
+ return pd.api.types.is_object_dtype(series) or pd.api.types.is_string_dtype(series)
82
+
83
+
84
+ def _add_value(old: pd.Series, value, text: str) -> pd.Series:
85
+ """*old* with *value* added at the end, keeping old's type where it can."""
86
+ old = old.reset_index(drop=True)
87
+ if not old.notna().any():
88
+ # No type to keep: infer one (Int64, Float64, boolean, string, ...)
89
+ values = [None] * len(old) + [value]
90
+ try:
91
+ return pd.Series(pd.array(values), name=old.name)
92
+ except (TypeError, ValueError):
93
+ return pd.Series(values, dtype=object, name=old.name)
94
+ if value is not None:
95
+ if _is_text(old) and not isinstance(value, str):
96
+ value = text # an id column of "007"s stays text
97
+ elif isinstance(value, str) and not _is_text(old):
98
+ logger.warning(
99
+ f"append: column {old.name!r} has no text values; {text!r} "
100
+ "makes it a text column"
101
+ )
102
+ old = old.map(lambda v: None if pd.isna(v) else str(v)).astype(object)
103
+ # Types that can hold a missing value, for the new cell
104
+ if pd.api.types.is_bool_dtype(old) and old.dtype == bool:
105
+ old = old.astype("boolean")
106
+ elif pd.api.types.is_integer_dtype(old) and old.dtype.kind in "iu":
107
+ old = old.astype("Int64")
108
+ out = old.reindex(range(len(old) + 1))
109
+ if value is not None:
110
+ try:
111
+ out.iloc[-1] = value
112
+ except (TypeError, ValueError):
113
+ out = out.astype(object)
114
+ out.iloc[-1] = value
115
+ return out
116
+
117
+
118
+ def _combine(df: pd.DataFrame, values: dict, texts: dict, fill) -> pd.DataFrame:
119
+ """*df* with the new row at the end; new columns go last, empty above."""
120
+ fill_text = "" if fill is None else str(fill)
121
+ columns = list(df.columns) + [c for c in values if c not in df.columns]
122
+ out = {}
123
+ for col in columns:
124
+ old = df[col] if col in df.columns else pd.Series([fill] * len(df), name=col)
125
+ value = values.get(col, fill)
126
+ out[col] = _add_value(old, value, texts.get(col, fill_text))
127
+ result = pd.DataFrame(out, columns=columns)
128
+ result.attrs = dict(df.attrs)
129
+ return result
130
+
131
+
132
+ def _check_strict(names, values: dict, path: str) -> None:
133
+ new = [c for c in values if c not in names]
134
+ if new:
135
+ raise ValueError(f"--strict: {new} not in {path} (columns: {list(names)})")
136
+
137
+
138
+ # ---------------------------------------------------------------------------
139
+ # --inplace
140
+ # ---------------------------------------------------------------------------
141
+
142
+
143
+ @contextlib.contextmanager
144
+ def _locked(path: str):
145
+ """Hold an exclusive lock on *path*'s directory (no lock file left behind).
146
+
147
+ The directory, not the file, is locked: a rewrite replaces the file, and a
148
+ lock on the old one would not stop a second writer.
149
+ """
150
+ try:
151
+ import fcntl
152
+ except ImportError: # Windows: no locking
153
+ yield
154
+ return
155
+ fd = os.open(os.path.dirname(os.path.abspath(path)), os.O_RDONLY)
156
+ try:
157
+ fcntl.flock(fd, fcntl.LOCK_EX)
158
+ yield
159
+ finally:
160
+ os.close(fd) # releases the lock
161
+
162
+
163
+ def _replace(path: str, write) -> None:
164
+ """Write a new *path* with write(tmp_path), then swap it in."""
165
+ folder = os.path.dirname(os.path.abspath(path))
166
+ name = os.path.basename(path)
167
+ fd, tmp = tempfile.mkstemp(prefix=f".{name}.", suffix=".tmp", dir=folder)
168
+ os.close(fd)
169
+ try:
170
+ write(tmp)
171
+ if os.path.exists(path):
172
+ shutil.copymode(path, tmp)
173
+ else: # mkstemp makes it private; use the usual mode
174
+ umask = os.umask(0)
175
+ os.umask(umask)
176
+ os.chmod(tmp, 0o666 & ~umask)
177
+ os.replace(tmp, path)
178
+ except BaseException:
179
+ with contextlib.suppress(FileNotFoundError):
180
+ os.unlink(tmp)
181
+ raise
182
+
183
+
184
+ def _tsv_text(df: pd.DataFrame, digits: int | None, header: bool) -> str:
185
+ """*df* as io.printdf writes TSV."""
186
+ buf = _io.StringIO()
187
+ _write_tsv(
188
+ docformats.nested_as_text(df),
189
+ buf,
190
+ sep="\t",
191
+ index=False,
192
+ float_format=f"%.{digits}g" if digits is not None else None,
193
+ header=header,
194
+ quoting=csv.QUOTE_NONE,
195
+ doublequote=False,
196
+ )
197
+ return buf.getvalue()
198
+
199
+
200
+ def _write_text(path: str, text: str) -> None:
201
+ with open(path, "w", encoding="utf-8", newline="") as fh:
202
+ fh.write(text)
203
+
204
+
205
+ def _ends_with_newline(path: str) -> bool:
206
+ with open(path, "rb") as fh:
207
+ fh.seek(-1, os.SEEK_END)
208
+ return fh.read(1) == b"\n"
209
+
210
+
211
+ def _append_text(path: str, text: str) -> None:
212
+ """Add *text* (whole lines) at the end of *path*, after a newline."""
213
+ if os.path.getsize(path) and not _ends_with_newline(path):
214
+ text = "\n" + text
215
+ with open(path, "a", encoding="utf-8", newline="") as fh:
216
+ fh.write(text)
217
+
218
+
219
+ def _inplace_tsv(path: str, values, texts, args) -> None:
220
+ exists = os.path.exists(path) and os.path.getsize(path) > 0
221
+ if exists:
222
+ with open(path, encoding="utf-8", newline="") as fh:
223
+ names = fh.readline().rstrip("\r\n").split("\t")
224
+ if args.strict:
225
+ _check_strict(names, values, path)
226
+ if all(c in names for c in values) and len(set(names)) == len(names):
227
+ # The usual case: one more line at the end
228
+ row = {c: values.get(c, args.fill) for c in names}
229
+ row_df = _combine(pd.DataFrame(columns=names), row, texts, args.fill)
230
+ _append_text(path, _tsv_text(row_df, args.digits, header=False))
231
+ return
232
+ # As text: the rows above are written back exactly as they were
233
+ df = pd.read_csv(
234
+ path,
235
+ sep="\t",
236
+ dtype=str,
237
+ keep_default_na=False,
238
+ na_values=[""],
239
+ quoting=csv.QUOTE_NONE,
240
+ )
241
+ else:
242
+ df = pd.DataFrame()
243
+ out = _combine(df, values, texts, args.fill)
244
+ text = _tsv_text(out, args.digits, header=True)
245
+ _replace(path, lambda tmp: _write_text(tmp, text))
246
+
247
+
248
+ def _inplace_parquet(path: str, values, texts, args) -> None:
249
+ if args.timestamp is not None: # parquet has a timestamp type
250
+ values = {**values, args.timestamp: pd.Timestamp(values[args.timestamp])}
251
+ if os.path.exists(path):
252
+ df = pd.read_parquet(path)
253
+ df.attrs["_parquet_meta"] = _read_parquet_meta(path)
254
+ if args.strict:
255
+ _check_strict(df.columns, values, path)
256
+ else:
257
+ df = pd.DataFrame()
258
+ out = _combine(df, values, texts, args.fill)
259
+ _replace(path, lambda tmp: _write_parquet(out, tmp))
260
+
261
+
262
+ def _inplace_jsonl(path: str, values, texts, args) -> None:
263
+ if args.strict and os.path.exists(path):
264
+ names: set = set()
265
+ with open(path, encoding="utf-8") as fh:
266
+ for line in fh:
267
+ if line.strip():
268
+ names.update(json.loads(line))
269
+ _check_strict(names, values, path)
270
+ # Records need not share keys: no fill, nothing to rewrite
271
+ row_df = _combine(pd.DataFrame(), values, texts, None)
272
+ buf = _io.StringIO()
273
+ docformats.write_json(row_df, buf, lines=True, digits=args.digits)
274
+ if os.path.exists(path):
275
+ _append_text(path, buf.getvalue())
276
+ else:
277
+ _write_text(path, buf.getvalue())
278
+
279
+
280
+ def _inplace(args: argparse.Namespace, values: dict, texts: dict) -> None:
281
+ path = args.DATAFILE
282
+ if path in (None, "-", "..."):
283
+ raise ValueError("--inplace needs a FILE to add the row to")
284
+ others = [
285
+ f"--{dest}"
286
+ for dest, default in args.io_defaults.items()
287
+ if dest not in _INPLACE_OPTIONS and getattr(args, dest, default) != default
288
+ ]
289
+ if others:
290
+ raise ValueError(f"--inplace can't be combined with {', '.join(others)}")
291
+ if args.strict and not os.path.exists(path):
292
+ raise ValueError(f"--strict: {path} does not exist")
293
+ ext = os.path.splitext(path)[1].lower()
294
+ if ext in (".json", ".md", ".tex"):
295
+ raise ValueError(
296
+ f"--inplace works on TSV, .jsonl and .parquet files, not {ext} "
297
+ "(a JSON log is best kept as .jsonl)"
298
+ )
299
+ with _locked(path):
300
+ if ext == ".parquet":
301
+ _inplace_parquet(path, values, texts, args)
302
+ elif ext == ".jsonl":
303
+ _inplace_jsonl(path, values, texts, args)
304
+ else:
305
+ _inplace_tsv(path, values, texts, args)
306
+
307
+
308
+ def _has_stdin_data() -> bool:
309
+ """True if stdin is a pipe or file with data (waits for it, or for EOF)."""
310
+ try:
311
+ if sys.stdin is None or sys.stdin.isatty():
312
+ return False
313
+ return bool(sys.stdin.buffer.peek(1))
314
+ except (AttributeError, OSError, ValueError): # no real stdin (pytest)
315
+ return False
316
+
317
+
318
+ _EPILOG = """\
319
+ VALUES
320
+ ------
321
+ -c COL=VALUE, repeatable. A value is a number (42, 1.5, 1e-3), true or
322
+ false, or text; quote it to keep it text ('"007"'), and leave it empty for a
323
+ missing value (note=). Without input, append makes a one-row table:
324
+
325
+ dftk append -c sample=S12 -c reads=48213 -c status=ok
326
+ dftk append -c sample=S12 -c reads=48213 -c ok=true --format json
327
+
328
+ ADDING TO A TABLE
329
+ -----------------
330
+ Columns not given are left empty (--fill VALUE fills them), and a new column
331
+ goes at the end, empty in the rows above. A value keeps its column's type
332
+ where it can ('007' stays text in a text column):
333
+
334
+ dftk append data.tsv -c id=x99 -c score=0.5
335
+ dftk dataset tips -o | dftk append -c total_bill=20 -c tip=4 -c day=Sun \\
336
+ | tail -n 3
337
+
338
+ STATUS LOGS (--inplace)
339
+ -----------------------
340
+ --inplace adds the row to the file itself, creating it if missing. Parallel
341
+ jobs can write to the same log: the file's directory is locked while each row
342
+ is written. --timestamp [COL] adds the local time as ISO 8601 text
343
+ (2026-11-09T19:13:57; a timestamp in .parquet), and --strict
344
+ refuses columns the file doesn't have, so a typo can't start a new one:
345
+
346
+ dftk append runs.tsv --inplace -c step=align -c status=ok --timestamp
347
+ dftk append runs.tsv --inplace -c step=call -c status=ok --timestamp --strict
348
+
349
+ A .jsonl log needs no matching columns at all: each line is one record.
350
+ Read it back with query --sql:
351
+
352
+ dftk append runs.jsonl --inplace -c step=align -c reads=48213 --timestamp
353
+ dftk query --sql "SELECT * FROM 'runs.jsonl'"
354
+
355
+ A row whose columns are all in a TSV header, and any .jsonl row, is written
356
+ as one more line; a new column, or a .parquet file, rewrites the file. For
357
+ many rows at once, use concat.
358
+ """
359
+
360
+
361
+ class AppendCommand(BaseCommand):
362
+ name = "append"
363
+ help = "Add one row (-c COL=VALUE); --inplace adds it to a file, e.g. a log."
364
+
365
+ def add_arguments(self, parser: argparse.ArgumentParser) -> None:
366
+ parser.formatter_class = argparse.RawDescriptionHelpFormatter
367
+ parser.epilog = _EPILOG
368
+
369
+ first = len(parser._actions)
370
+ self.add_io_arguments(parser)
371
+ parser.set_defaults(
372
+ io_defaults={a.dest: a.default for a in parser._actions[first:]}
373
+ )
374
+
375
+ g = parser.add_argument_group("append")
376
+ g.add_argument(
377
+ "-c",
378
+ "--col",
379
+ dest="constant",
380
+ action="append",
381
+ default=[],
382
+ metavar="COL=VALUE",
383
+ help="A value of the new row; repeatable.",
384
+ )
385
+ g.add_argument(
386
+ "--inplace",
387
+ action="store_true",
388
+ help="Add the row to DATAFILE itself (created if missing).",
389
+ )
390
+ g.add_argument(
391
+ "--timestamp",
392
+ nargs="?",
393
+ const="timestamp",
394
+ default=None,
395
+ metavar="COL",
396
+ help="Add the current local time, to the second, as ISO 8601 text "
397
+ "(2026-11-09T19:13:57) (column: timestamp).",
398
+ )
399
+ g.add_argument(
400
+ "--fill",
401
+ default=None,
402
+ metavar="VALUE",
403
+ help="Value for columns the row doesn't give, and for a new "
404
+ "column in the rows above (default: empty).",
405
+ )
406
+ g.add_argument(
407
+ "--strict",
408
+ action="store_true",
409
+ help="Refuse columns the table doesn't have.",
410
+ )
411
+
412
+ def execute(self, args: argparse.Namespace) -> None:
413
+ values, texts = _row(args)
414
+ args.fill = None if args.fill is None else parse_value(args.fill)
415
+ if args.inplace:
416
+ _inplace(args, values, texts)
417
+ return
418
+ if args.DATAFILE is not None or _has_stdin_data():
419
+ df = io.read(args)
420
+ else:
421
+ df = pd.DataFrame()
422
+ if args.strict:
423
+ _check_strict(df.columns, values, args.DATAFILE or "the input")
424
+ io.printdf(_combine(df, values, texts, args.fill), args)