dataframe-toolkit 0.16.0__tar.gz → 0.17.1__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.16.0 → dataframe_toolkit-0.17.1}/PKG-INFO +22 -1
  2. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/README.md +21 -0
  3. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/__init__.py +1 -0
  6. dataframe_toolkit-0.17.1/src/dftk/commands/append_cmd.py +424 -0
  7. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/eval_cmd.py +12 -6
  8. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/common/io.py +30 -13
  9. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/skills/dftk/SKILL.md +8 -1
  10. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/__init__.py +0 -0
  11. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/cli.py +0 -0
  12. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/annotate_cmd.py +0 -0
  13. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/base.py +0 -0
  14. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/binx_cmd.py +0 -0
  15. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/chi_cmd.py +0 -0
  16. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/clean_cmd.py +0 -0
  17. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/cleannames_cmd.py +0 -0
  18. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/concat_cmd.py +0 -0
  19. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/corr_cmd.py +0 -0
  20. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/dataset_cmd.py +0 -0
  21. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/describe_cmd.py +0 -0
  22. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/explode_cmd.py +0 -0
  23. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/fit_cmd.py +0 -0
  24. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/func_cmd.py +0 -0
  25. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/heatmap_cmd.py +0 -0
  26. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/help.py +0 -0
  27. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/hist_cmd.py +0 -0
  28. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/implode_cmd.py +0 -0
  29. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/info_cmd.py +0 -0
  30. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/interp_cmd.py +0 -0
  31. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/line_cmd.py +0 -0
  32. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/melt_cmd.py +0 -0
  33. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/merge_cmd.py +0 -0
  34. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/pairs_cmd.py +0 -0
  35. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/pivot_cmd.py +0 -0
  36. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/print_cmd.py +0 -0
  37. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/query_cmd.py +0 -0
  38. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/randvar_cmd.py +0 -0
  39. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/sample_cmd.py +0 -0
  40. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/scale_cmd.py +0 -0
  41. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/scat_cmd.py +0 -0
  42. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/segid_cmd.py +0 -0
  43. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/skill_cmd.py +0 -0
  44. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/split_cmd.py +0 -0
  45. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/stat_cmd.py +0 -0
  46. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/test_cmd.py +0 -0
  47. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/transpose_cmd.py +0 -0
  48. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/commands/wstat_cmd.py +0 -0
  49. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/common/__init__.py +0 -0
  50. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/common/copula.py +0 -0
  51. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/common/docformats.py +0 -0
  52. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/common/evalfuncs.py +0 -0
  53. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/common/plot.py +0 -0
  54. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/common/seed.py +0 -0
  55. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/common/seq.py +0 -0
  56. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/common/stats.py +0 -0
  57. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/src/dftk/io.py +0 -0
  58. {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.1}/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.16.0
3
+ Version: 0.17.1
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` |
@@ -238,6 +239,26 @@ dftk query --sql "SELECT * FROM 'catalog.jsonl' WHERE locus LIKE 'ATXN%'" --form
238
239
  # ]
239
240
  ```
240
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
+
241
262
  ### Large tables: hexbin instead of points
242
263
 
243
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:
@@ -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` |
@@ -208,6 +209,26 @@ dftk query --sql "SELECT * FROM 'catalog.jsonl' WHERE locus LIKE 'ATXN%'" --form
208
209
  # ]
209
210
  ```
210
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
+
211
232
  ### Large tables: hexbin instead of points
212
233
 
213
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:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dataframe-toolkit"
3
- version = "0.16.0"
3
+ version = "0.17.1"
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.16.0"
3
+ version = "0.17.1"
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"),
@@ -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)
@@ -173,7 +173,9 @@ Add a column with a fixed value:
173
173
  dftk dataset tips -o | dftk eval -c "batch = 3"
174
174
  dftk dataset tips -o | dftk eval -c "region = northeast"
175
175
 
176
- The value is coerced to numeric when possible.
176
+ The value is coerced to numeric when possible; quote it to keep it text:
177
+
178
+ dftk dataset tips -o | dftk eval -c 'code = "007"'
177
179
 
178
180
 
179
181
  STRING / ROW FUNCTIONS (-s)
@@ -288,13 +290,17 @@ def _eval(df: pd.DataFrame, args: argparse.Namespace) -> pd.DataFrame:
288
290
  # -c: constant columns
289
291
  for expr in getattr(args, "constant", []):
290
292
  colname, constval_str = (x.strip() for x in expr.split("=", 1))
291
- try:
292
- constval: int | float | str = int(constval_str)
293
- except ValueError:
293
+ quoted = len(constval_str) >= 2 and constval_str[0] == constval_str[-1]
294
+ if quoted and constval_str[0] in "\"'":
295
+ constval: int | float | str = constval_str[1:-1] # "007" stays text
296
+ else:
294
297
  try:
295
- constval = float(constval_str)
298
+ constval = int(constval_str)
296
299
  except ValueError:
297
- constval = constval_str
300
+ try:
301
+ constval = float(constval_str)
302
+ except ValueError:
303
+ constval = constval_str
298
304
  df[colname] = constval
299
305
 
300
306
  # -f: special functions, or else pandas df.eval
@@ -645,14 +645,16 @@ class io:
645
645
  sort_group = g.add_mutually_exclusive_group()
646
646
  sort_group.add_argument(
647
647
  "--sortasc",
648
- help="Sort ascending by named columns.",
648
+ help="Sort ascending by the named columns; without names, by "
649
+ "every column, left to right.",
649
650
  nargs="*",
650
651
  default=None,
651
652
  metavar="COL",
652
653
  )
653
654
  sort_group.add_argument(
654
655
  "--sortdesc",
655
- help="Sort descending by named columns.",
656
+ help="Sort descending by the named columns; without names, by "
657
+ "every column, left to right.",
656
658
  nargs="*",
657
659
  default=None,
658
660
  metavar="COL",
@@ -757,24 +759,39 @@ class io:
757
759
  except Exception:
758
760
  logging.warning(f"--cast: failed for {item!r}")
759
761
 
760
- # Sort
762
+ # Sort; --sortasc or --sortdesc without names sorts by every column,
763
+ # left to right
761
764
  sortcols: list[str] = []
762
765
  sortdirs: list[bool] = []
763
- if getattr(args, "sortasc", None) is not None:
764
- sortcols += args.sortasc
765
- sortdirs += [True] * len(args.sortasc)
766
- if getattr(args, "sortdesc", None) is not None:
767
- sortcols += args.sortdesc
768
- sortdirs += [False] * len(args.sortdesc)
766
+ for option, ascending in (("sortasc", True), ("sortdesc", False)):
767
+ names = getattr(args, option, None)
768
+ if names is not None:
769
+ names = names or list(df.columns)
770
+ sortcols += names
771
+ sortdirs += [ascending] * len(names)
769
772
  for item in getattr(args, "sort", None) or []:
770
- col, direction = item.split(":")
773
+ col, sep, direction = item.rpartition(":")
774
+ if not sep or direction.lower() not in ("a", "d"):
775
+ raise ValueError(f"--sort expects COL:a or COL:d, got {item!r}")
771
776
  sortcols.append(col)
772
- sortdirs.append(direction.lower() != "d")
777
+ sortdirs.append(direction.lower() == "a")
773
778
  if sortcols:
779
+ missing = [c for c in sortcols if c not in df.columns]
780
+ if missing:
781
+ hint = ""
782
+ if any(os.path.exists(c) for c in missing):
783
+ hint = (
784
+ " A file name was read as a column: put the file "
785
+ "before --sortasc/--sortdesc, or end the list with --"
786
+ )
787
+ raise ValueError(
788
+ f"--sort: column(s) not found: {missing}. Available "
789
+ f"columns: {list(df.columns)}.{hint}"
790
+ )
774
791
  try:
775
792
  df = df.sort_values(by=sortcols, ascending=sortdirs)
776
- except Exception as exc:
777
- logging.warning(f"--sort failed: {exc}")
793
+ except TypeError as exc: # e.g. numbers and text in one column
794
+ raise ValueError(f"--sort failed on {sortcols}: {exc}") from exc
778
795
 
779
796
  # Drop columns
780
797
  for pattern in getattr(args, "drop", None) or []:
@@ -82,7 +82,8 @@ Input: `--prequery EXPR` (filter rows right after reading), `--noheader`
82
82
  Output, applied after the command's own work: `--select COL… [+]` (choose
83
83
  and order columns; globs allowed; a trailing `+` keeps the remaining
84
84
  columns), `--drop COL…`, `--move OLD:NEW…` (rename), `--postquery EXPR`,
85
- `--sortasc COL…` / `--sortdesc COL…` / `--sort COL:a COL:d`,
85
+ `--sortasc [COL…]` / `--sortdesc [COL…]` (no names: every column, left to
86
+ right; give the file before them) / `--sort COL:a COL:d`,
86
87
  `--round COL:N`, `--digits N`, `--cast COL:TYPE`, `--deduplicate [COL…]`,
87
88
  `--dropna`, `--na_rep VAL`, `--removeheader`, and
88
89
  `--meta KEY=VALUE` (provenance, see below).
@@ -113,6 +114,8 @@ Transform:
113
114
  | Read JSON or JSON Lines (no input needed); flatten nested fields with `pos.*`, lists with `unnest()` | `query --sql "SELECT * EXCLUDE (pos), pos.* FROM 'f.jsonl'"` |
114
115
  | Join two tables, including anti-joins | `merge DATAFILE -r OTHER -k KEY [-t left] [--only left]` |
115
116
  | Stack tables row-wise | `concat A B C [--sourcecol src]` |
117
+ | Add one row (`-c COL=VALUE`; columns not given stay empty); without input, a one-row table, also as JSON (`--format json`) | `append [FILE] -c COL=VALUE … [--fill V] [--strict]` |
118
+ | Add a row to a status log file in place (created if missing, safe for parallel jobs; `.tsv`, `.jsonl` or `.parquet`) | `append log.tsv --inplace -c step=X -c status=ok --timestamp [--strict]` |
116
119
  | Wide to long / long to wide plus aggregation | `melt` / `pivot -i ROWS -g COLS -v VALS -f FUNCS` |
117
120
  | Split comma-separated values in a cell into one row each, repeating the other columns | `explode -c COL [--sep SEP]` |
118
121
  | Join a column's values within groups of rows into one cell (`GO:1,GO:2`), the inverse of explode | `implode -c COL [-i KEYS] [--unique] [--sortvalues]` |
@@ -202,6 +205,10 @@ dftk annotate clean.parquet --get build
202
205
  Annotations read from an input are written again on every parquet output;
203
206
  `--meta` adds keys or overrides them. TSV output has no metadata.
204
207
 
208
+ `append -c` values: numbers and `true`/`false` are typed, `'"007"'` (quoted)
209
+ stays text, `note=` is empty. In a TSV log, existing rows are never changed;
210
+ a new column is added at the end (`--strict` refuses one, to catch typos).
211
+
205
212
  ## Make and Snakemake
206
213
 
207
214
  For rules in workflows (named outputs, wildcards, logs, provenance, when to