dataframe-toolkit 0.16.0__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.
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/PKG-INFO +22 -1
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/README.md +21 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/pyproject.toml +1 -1
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/pyproject.toml.orig +1 -1
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/__init__.py +1 -0
- dataframe_toolkit-0.17.0/src/dftk/commands/append_cmd.py +424 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/eval_cmd.py +12 -6
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/skills/dftk/SKILL.md +6 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/__init__.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/cli.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/annotate_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/base.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/binx_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/chi_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/clean_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/cleannames_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/concat_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/corr_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/dataset_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/describe_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/explode_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/fit_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/func_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/heatmap_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/help.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/hist_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/implode_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/info_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/interp_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/line_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/melt_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/merge_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/pairs_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/pivot_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/print_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/query_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/randvar_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/sample_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/scale_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/scat_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/segid_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/skill_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/split_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/stat_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/test_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/transpose_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/commands/wstat_cmd.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/common/__init__.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/common/copula.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/common/docformats.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/common/evalfuncs.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/common/io.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/common/plot.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/common/seed.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/common/seq.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/common/stats.py +0 -0
- {dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/io.py +0 -0
- {dataframe_toolkit-0.16.0 → 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.
|
|
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` |
|
|
@@ -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:
|
|
@@ -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
|
-
|
|
292
|
-
|
|
293
|
-
|
|
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 =
|
|
298
|
+
constval = int(constval_str)
|
|
296
299
|
except ValueError:
|
|
297
|
-
|
|
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
|
|
@@ -113,6 +113,8 @@ Transform:
|
|
|
113
113
|
| 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
114
|
| Join two tables, including anti-joins | `merge DATAFILE -r OTHER -k KEY [-t left] [--only left]` |
|
|
115
115
|
| Stack tables row-wise | `concat A B C [--sourcecol src]` |
|
|
116
|
+
| 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]` |
|
|
117
|
+
| 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
118
|
| Wide to long / long to wide plus aggregation | `melt` / `pivot -i ROWS -g COLS -v VALS -f FUNCS` |
|
|
117
119
|
| Split comma-separated values in a cell into one row each, repeating the other columns | `explode -c COL [--sep SEP]` |
|
|
118
120
|
| 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 +204,10 @@ dftk annotate clean.parquet --get build
|
|
|
202
204
|
Annotations read from an input are written again on every parquet output;
|
|
203
205
|
`--meta` adds keys or overrides them. TSV output has no metadata.
|
|
204
206
|
|
|
207
|
+
`append -c` values: numbers and `true`/`false` are typed, `'"007"'` (quoted)
|
|
208
|
+
stays text, `note=` is empty. In a TSV log, existing rows are never changed;
|
|
209
|
+
a new column is added at the end (`--strict` refuses one, to catch typos).
|
|
210
|
+
|
|
205
211
|
## Make and Snakemake
|
|
206
212
|
|
|
207
213
|
For rules in workflows (named outputs, wildcards, logs, provenance, when to
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{dataframe_toolkit-0.16.0 → dataframe_toolkit-0.17.0}/src/dftk/skills/dftk/references/snakemake.md
RENAMED
|
File without changes
|