dataframe-toolkit 0.19.0__tar.gz → 0.21.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 (62) hide show
  1. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/PKG-INFO +31 -15
  2. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/README.md +30 -14
  3. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/chi_cmd.py +2 -2
  6. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/eval_cmd.py +4 -2
  7. dataframe_toolkit-0.21.0/src/dftk/commands/func_cmd.py +363 -0
  8. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/hist_cmd.py +2 -2
  9. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/line_cmd.py +2 -2
  10. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/manhattan_cmd.py +268 -24
  11. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/qq_cmd.py +26 -3
  12. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/scat_cmd.py +2 -2
  13. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/common/gwas.py +55 -11
  14. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/common/io.py +59 -7
  15. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/skills/dftk/SKILL.md +5 -3
  16. dataframe_toolkit-0.19.0/src/dftk/commands/func_cmd.py +0 -187
  17. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/__init__.py +0 -0
  18. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/cli.py +0 -0
  19. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/__init__.py +0 -0
  20. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/annotate_cmd.py +0 -0
  21. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/append_cmd.py +0 -0
  22. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/base.py +0 -0
  23. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/binx_cmd.py +0 -0
  24. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/clean_cmd.py +0 -0
  25. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  26. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/concat_cmd.py +0 -0
  27. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/corr_cmd.py +0 -0
  28. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/dataset_cmd.py +0 -0
  29. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/describe_cmd.py +0 -0
  30. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/explode_cmd.py +0 -0
  31. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/fit_cmd.py +0 -0
  32. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/heatmap_cmd.py +0 -0
  33. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/help.py +0 -0
  34. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/implode_cmd.py +0 -0
  35. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/info_cmd.py +0 -0
  36. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/interp_cmd.py +0 -0
  37. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/melt_cmd.py +0 -0
  38. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/merge_cmd.py +0 -0
  39. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/pairs_cmd.py +0 -0
  40. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/pivot_cmd.py +0 -0
  41. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/print_cmd.py +0 -0
  42. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/query_cmd.py +0 -0
  43. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/randvar_cmd.py +0 -0
  44. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/sample_cmd.py +0 -0
  45. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/scale_cmd.py +0 -0
  46. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/segid_cmd.py +0 -0
  47. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/skill_cmd.py +0 -0
  48. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/split_cmd.py +0 -0
  49. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/stat_cmd.py +0 -0
  50. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/test_cmd.py +0 -0
  51. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/transpose_cmd.py +0 -0
  52. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/wstat_cmd.py +0 -0
  53. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/common/__init__.py +0 -0
  54. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/common/copula.py +0 -0
  55. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/common/docformats.py +0 -0
  56. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/common/evalfuncs.py +0 -0
  57. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/common/plot.py +0 -0
  58. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/common/seed.py +0 -0
  59. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/common/seq.py +0 -0
  60. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/common/stats.py +0 -0
  61. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.0}/src/dftk/io.py +0 -0
  62. {dataframe_toolkit-0.19.0 → dataframe_toolkit-0.21.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.19.0
3
+ Version: 0.21.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
@@ -131,7 +131,7 @@ dftk dataset tips -o \
131
131
  | `explode` | Split separated values in a cell (`a,b`) into one row per value |
132
132
  | `implode` | Join a column's values within groups into one cell, the inverse of `explode` |
133
133
  | `pivot` | Reshape long-to-wide with per-cell aggregation |
134
- | `func` | Column transforms: cumsum, group mean/sum/min/max/count/median/std, rank, qcut:N |
134
+ | `func` | Column transforms: cumsum, group mean/sum/min/max/count/median/std, rank, qcut:N; interpolate/ffill/bfill within groups by an x column |
135
135
  | `scale` | Normalise: z-score, min-shift, sum/max/mean scaling, Blom rank, regression residuals |
136
136
  | `interp` | Interpolate values from a reference curve into a table (1-D lookup) |
137
137
  | `binx` | Assign bin indices to a column based on explicit or generated edges |
@@ -345,8 +345,9 @@ dftk dataset co2 -o | dftk eval -f "ffill = co2.ffill()" \
345
345
 
346
346
  `ffill` leaves the first rows empty and `bfill` the last ones;
347
347
  `x.ffill().fillna(x.bfill())` fills both. `interpolate()` counts one step
348
- per row, so the rows must be evenly spaced; for an x-based lookup from a
349
- reference curve, see `dftk interp`.
348
+ per row, so the rows must be evenly spaced; for unevenly spaced rows use
349
+ `func -t interpolate --xcol X` (below), and for a lookup from a reference
350
+ curve, `dftk interp`.
350
351
 
351
352
  **Row order and groups.** These methods use the rows in the order they are
352
353
  in. Sort first, in a step of its own: `--sortasc` applies to a command's
@@ -362,21 +363,25 @@ dftk dataset healthexp -o \
362
363
  | dftk eval -f "le_filled = le.groupby(Country).ffill()"
363
364
  ```
364
365
 
365
- `interpolate()` has no grouped form. Once each group's rows are together,
366
- gaps inside a group are right, but a gap at a group's start or end is
367
- filled from the neighbouring group. To leave those empty, keep only values
368
- with something before and after them in the same group:
366
+ For interpolation within groups, `func -t interpolate` does it in one
367
+ step. It draws the line against an x column (`--xcol`, required), so
368
+ unevenly spaced rows (missing years, genome positions) get the right
369
+ values; it takes each group's rows in X order itself, so no sort step is
370
+ needed, and it leaves gaps before a group's first value or after its last
371
+ empty. `-t ffill` and `-t bfill` work the same way; chained after
372
+ `interpolate` on the same column (`-d`), they fill those ends too:
369
373
 
370
374
  ```bash
371
375
  dftk dataset healthexp -o \
372
- | dftk eval -f "le = Life_Expectancy.where(Year % 10 != 5)" \
373
- --sortasc Country Year -o \
374
- | dftk eval -f "before = le.groupby(Country).ffill().notna()" \
375
- -f "after = le.groupby(Country).bfill().notna()" \
376
- -f "le_linear = le.interpolate().where(before & after)" \
377
- --drop before after
376
+ | dftk eval -f "le = Life_Expectancy.where(Year % 10 != 5)" -o \
377
+ | dftk func -c le -t interpolate -g Country --xcol Year -d le_filled -o \
378
+ | dftk func -c le_filled -t ffill -g Country --xcol Year -d le_filled -o \
379
+ | dftk func -c le_filled -t bfill -g Country --xcol Year -d le_filled
378
380
  ```
379
381
 
382
+ `eval`'s `interpolate()` counts one step per row: with 10 at x=2 and 14 at
383
+ x=6, it gives the gap at x=5 12.0, where `func --xcol` gives 13.0.
384
+
380
385
  ### Differences between rows
381
386
 
382
387
  For the change in a column from one row to the next, `eval -f` takes
@@ -484,7 +489,16 @@ A p-value below about 1e-308 is stored as 0, which plots as -log10(p) = 323 with
484
489
  dftk dataset gwas -o | dftk manhattan --chi2col Chisq -f manhattan.png
485
490
  ```
486
491
 
487
- Points with p > 0.01 are thinned to one per cell of a grid finer than the figure (`--no-thin` draws all), and points are rasterized: ten million variants take a few seconds and a PDF stays small. `--ylim LO HI` caps the axis, with points above it drawn as triangles on the top edge. Several scans in one table: `--subgraphcol study` draws a panel each, `-g study` a colour each.
492
+ Points with p > 0.01 are thinned to one per cell of a grid finer than the figure (`--no-thin` draws all), and points are rasterized: ten million variants take a few seconds and a PDF stays small. `--ylim LO HI` caps the axis, with points above it drawn as triangles on the top edge. `--logy` instead keeps every peak: the axis is linear up to -log10(p) = 10 and logarithmic above it (`--logy 5` moves the switch), so a peak at 380 and one at 8 both show. `--sigcolor red` colours the points past the `--sig` line.
493
+
494
+ Several scans in one table: `--subgraphcol study` draws a panel each, `-g study` a colour each, and `--miami study` draws two of them face to face (a Miami plot): the first on top, the second upside down below it, with the chromosome numbers between them. The column must hold two values, or name the two to draw (`--miami study a b`, top first). Here the second scan is the example one with every chi-squared halved:
495
+
496
+ ```bash
497
+ dftk dataset gwas -o \
498
+ | dftk eval -f "half = Chisq / 2" --select Chr pos Chisq half -o \
499
+ | dftk melt -i Chr pos -d study -v chi2 -o \
500
+ | dftk manhattan --chi2col chi2 --miami study --sigcolor red -f miami.png
501
+ ```
488
502
 
489
503
  `qq` plots the same p-values (same column options, no chromosome or position needed) against what null tests would give, with a 95 % band (`--ci`) and the genomic inflation factor λ, the median chi-squared over its null median. A curve lifted off the diagonal from the start, λ above about 1.05, points to stratification or other inflation; a few points leaving it at the top are associations. With `-g`, each group gets its own curve and λ:
490
504
 
@@ -493,6 +507,8 @@ dftk dataset gwas -o | dftk qq -f qq.png
493
507
  dftk dataset gwas -o | dftk eval -f "Chisq = Chisq * 1.15" -o | dftk qq --chi2col Chisq -f qq.png
494
508
  ```
495
509
 
510
+ `qq --logy` makes its y axis linear up to 10 and logarithmic above, as in `manhattan`.
511
+
496
512
  ### Bootstrap confidence intervals
497
513
 
498
514
  Bootstrap mode repeats the full stat computation N times on resampled data
@@ -101,7 +101,7 @@ dftk dataset tips -o \
101
101
  | `explode` | Split separated values in a cell (`a,b`) into one row per value |
102
102
  | `implode` | Join a column's values within groups into one cell, the inverse of `explode` |
103
103
  | `pivot` | Reshape long-to-wide with per-cell aggregation |
104
- | `func` | Column transforms: cumsum, group mean/sum/min/max/count/median/std, rank, qcut:N |
104
+ | `func` | Column transforms: cumsum, group mean/sum/min/max/count/median/std, rank, qcut:N; interpolate/ffill/bfill within groups by an x column |
105
105
  | `scale` | Normalise: z-score, min-shift, sum/max/mean scaling, Blom rank, regression residuals |
106
106
  | `interp` | Interpolate values from a reference curve into a table (1-D lookup) |
107
107
  | `binx` | Assign bin indices to a column based on explicit or generated edges |
@@ -315,8 +315,9 @@ dftk dataset co2 -o | dftk eval -f "ffill = co2.ffill()" \
315
315
 
316
316
  `ffill` leaves the first rows empty and `bfill` the last ones;
317
317
  `x.ffill().fillna(x.bfill())` fills both. `interpolate()` counts one step
318
- per row, so the rows must be evenly spaced; for an x-based lookup from a
319
- reference curve, see `dftk interp`.
318
+ per row, so the rows must be evenly spaced; for unevenly spaced rows use
319
+ `func -t interpolate --xcol X` (below), and for a lookup from a reference
320
+ curve, `dftk interp`.
320
321
 
321
322
  **Row order and groups.** These methods use the rows in the order they are
322
323
  in. Sort first, in a step of its own: `--sortasc` applies to a command's
@@ -332,21 +333,25 @@ dftk dataset healthexp -o \
332
333
  | dftk eval -f "le_filled = le.groupby(Country).ffill()"
333
334
  ```
334
335
 
335
- `interpolate()` has no grouped form. Once each group's rows are together,
336
- gaps inside a group are right, but a gap at a group's start or end is
337
- filled from the neighbouring group. To leave those empty, keep only values
338
- with something before and after them in the same group:
336
+ For interpolation within groups, `func -t interpolate` does it in one
337
+ step. It draws the line against an x column (`--xcol`, required), so
338
+ unevenly spaced rows (missing years, genome positions) get the right
339
+ values; it takes each group's rows in X order itself, so no sort step is
340
+ needed, and it leaves gaps before a group's first value or after its last
341
+ empty. `-t ffill` and `-t bfill` work the same way; chained after
342
+ `interpolate` on the same column (`-d`), they fill those ends too:
339
343
 
340
344
  ```bash
341
345
  dftk dataset healthexp -o \
342
- | dftk eval -f "le = Life_Expectancy.where(Year % 10 != 5)" \
343
- --sortasc Country Year -o \
344
- | dftk eval -f "before = le.groupby(Country).ffill().notna()" \
345
- -f "after = le.groupby(Country).bfill().notna()" \
346
- -f "le_linear = le.interpolate().where(before & after)" \
347
- --drop before after
346
+ | dftk eval -f "le = Life_Expectancy.where(Year % 10 != 5)" -o \
347
+ | dftk func -c le -t interpolate -g Country --xcol Year -d le_filled -o \
348
+ | dftk func -c le_filled -t ffill -g Country --xcol Year -d le_filled -o \
349
+ | dftk func -c le_filled -t bfill -g Country --xcol Year -d le_filled
348
350
  ```
349
351
 
352
+ `eval`'s `interpolate()` counts one step per row: with 10 at x=2 and 14 at
353
+ x=6, it gives the gap at x=5 12.0, where `func --xcol` gives 13.0.
354
+
350
355
  ### Differences between rows
351
356
 
352
357
  For the change in a column from one row to the next, `eval -f` takes
@@ -454,7 +459,16 @@ A p-value below about 1e-308 is stored as 0, which plots as -log10(p) = 323 with
454
459
  dftk dataset gwas -o | dftk manhattan --chi2col Chisq -f manhattan.png
455
460
  ```
456
461
 
457
- Points with p > 0.01 are thinned to one per cell of a grid finer than the figure (`--no-thin` draws all), and points are rasterized: ten million variants take a few seconds and a PDF stays small. `--ylim LO HI` caps the axis, with points above it drawn as triangles on the top edge. Several scans in one table: `--subgraphcol study` draws a panel each, `-g study` a colour each.
462
+ Points with p > 0.01 are thinned to one per cell of a grid finer than the figure (`--no-thin` draws all), and points are rasterized: ten million variants take a few seconds and a PDF stays small. `--ylim LO HI` caps the axis, with points above it drawn as triangles on the top edge. `--logy` instead keeps every peak: the axis is linear up to -log10(p) = 10 and logarithmic above it (`--logy 5` moves the switch), so a peak at 380 and one at 8 both show. `--sigcolor red` colours the points past the `--sig` line.
463
+
464
+ Several scans in one table: `--subgraphcol study` draws a panel each, `-g study` a colour each, and `--miami study` draws two of them face to face (a Miami plot): the first on top, the second upside down below it, with the chromosome numbers between them. The column must hold two values, or name the two to draw (`--miami study a b`, top first). Here the second scan is the example one with every chi-squared halved:
465
+
466
+ ```bash
467
+ dftk dataset gwas -o \
468
+ | dftk eval -f "half = Chisq / 2" --select Chr pos Chisq half -o \
469
+ | dftk melt -i Chr pos -d study -v chi2 -o \
470
+ | dftk manhattan --chi2col chi2 --miami study --sigcolor red -f miami.png
471
+ ```
458
472
 
459
473
  `qq` plots the same p-values (same column options, no chromosome or position needed) against what null tests would give, with a 95 % band (`--ci`) and the genomic inflation factor λ, the median chi-squared over its null median. A curve lifted off the diagonal from the start, λ above about 1.05, points to stratification or other inflation; a few points leaving it at the top are associations. With `-g`, each group gets its own curve and λ:
460
474
 
@@ -463,6 +477,8 @@ dftk dataset gwas -o | dftk qq -f qq.png
463
477
  dftk dataset gwas -o | dftk eval -f "Chisq = Chisq * 1.15" -o | dftk qq --chi2col Chisq -f qq.png
464
478
  ```
465
479
 
480
+ `qq --logy` makes its y axis linear up to 10 and logarithmic above, as in `manhattan`.
481
+
466
482
  ### Bootstrap confidence intervals
467
483
 
468
484
  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.19.0"
3
+ version = "0.21.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.19.0"
3
+ version = "0.21.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -15,7 +15,7 @@ import numpy as np
15
15
 
16
16
  from dftk.commands.base import BaseCommand
17
17
  from dftk.common.copula import corner_chi, pseudo_observations
18
- from dftk.common.io import check_cols, io
18
+ from dftk.common.io import check_cols, io, option_columns
19
19
  from dftk.common.plot import (
20
20
  add_figure_arguments,
21
21
  add_group_arguments,
@@ -153,7 +153,7 @@ class ChiCommand(BaseCommand):
153
153
  if not args.xcol or not args.ycol:
154
154
  raise ValueError("--xcol (-x) and --ycol (-y) are required.")
155
155
 
156
- df = io.read(args)
156
+ df = io.read(args, columns=option_columns(args))
157
157
  check_cols(df, [args.xcol, args.ycol], "-x/-y")
158
158
  check_cols(df, args.groupcol, "-g/--groupcol")
159
159
  check_cols(df, args.subgraphcol, "--subgraphcol")
@@ -69,8 +69,10 @@ when the table holds several series, or values come from the next group:
69
69
  --sortasc Country Year -o \\
70
70
  | dftk eval -f "le_filled = le.groupby(Country).ffill()"
71
71
 
72
- interpolate() has no grouped form. The README ("Filling missing values")
73
- covers defaults from a merge, interpolating within groups, and more.
72
+ To interpolate within groups, or by an x column when rows are unevenly
73
+ spaced, use func: dftk func -c le -t interpolate -g Country --xcol Year
74
+ (it also has ffill and bfill in x order, with no sort step). The README
75
+ ("Filling missing values") covers defaults from a merge and more.
74
76
 
75
77
 
76
78
  DIFFERENCES BETWEEN ROWS (-f)
@@ -0,0 +1,363 @@
1
+ """
2
+ dftk.commands.func_cmd — dftk func subcommand.
3
+
4
+ Applies column transforms, optionally within groups. The main use case is
5
+ adding derived columns to a DataFrame: running totals, quantile bins, group-
6
+ level aggregates broadcast back to the original row count, etc.
7
+
8
+ TRANSFORMS (-t / --transform)
9
+ ------------------------------
10
+ sum Group sum broadcast to each row (or simple column sum).
11
+ mean Group mean broadcast to each row.
12
+ min Group min broadcast to each row.
13
+ max Group max broadcast to each row.
14
+ count Non-null count per group broadcast to each row.
15
+ median Group median broadcast to each row.
16
+ std Group standard deviation broadcast to each row.
17
+ cumsum Cumulative sum (within group when -g is given).
18
+ rank Rank within group (average method, ascending).
19
+ pct_rank Percentile rank within group (0–1).
20
+ qcut:N Assign each value to one of N equal-frequency quantile bins.
21
+ The bin label is an integer 1..N.
22
+ interpolate Fill empty cells on a straight line, against --xcol X,
23
+ between the known values before and after them (within each
24
+ group with -g), so unevenly spaced rows get the right values.
25
+ Gaps before a group's first value or after its last stay
26
+ empty: nothing is extrapolated.
27
+ ffill Fill empty cells with the value before them in --xcol order
28
+ (bfill: after), within each group.
29
+
30
+ FILLING GAPS (interpolate, ffill, bfill)
31
+ ----------------------------------------
32
+ These need -x/--xcol X (time, position, year, date, ...): the rows are
33
+ taken in X order within each group, whatever order the file is in, and
34
+ written back in the file's order, so no sort step is needed. Rows without
35
+ an X value are left as they are. Only empty cells are filled: a missing
36
+ row (a year with no row at all) is not added.
37
+
38
+ interpolate needs a numeric column, and a numeric or date X; its result is
39
+ always decimal (an integer column comes back as 1.0, 2.0, ...). Repeated X
40
+ values within a group are an error (which value would the line go
41
+ through?), even in a group with nothing to fill: average replicates first
42
+ (pivot) or add a replicate column to -g. ffill and bfill take any column
43
+ and any X that can be sorted (numbers, dates, text); rows with the same X
44
+ keep their file order.
45
+
46
+ For no gaps at all, chain all three on the same column (-d): interpolate,
47
+ then ffill carries the last known value on to the end and bfill the first
48
+ known value back to the start.
49
+
50
+ interpolate handles one group at a time: a million rows in 10,000 groups
51
+ take about half a second, but a million groups of one or two rows take
52
+ about ten seconds. ffill and bfill don't depend on the number of groups.
53
+
54
+ EXAMPLES
55
+ --------
56
+ Cumulative sum of "value":
57
+
58
+ dftk func data.tsv -c value -t cumsum
59
+ dftk dataset tips -o | dftk func -c total_bill -t cumsum
60
+
61
+ Group mean broadcast (adds "total_bill_mean" unless -d is given):
62
+
63
+ dftk dataset tips -o | dftk func -c total_bill -g day -t mean
64
+
65
+ Quantile bins (quartiles):
66
+
67
+ dftk dataset tips -o | dftk func -c tip -t qcut:4 -d tip_quartile
68
+
69
+ Fill gaps in life expectancy (here every year ending in 5 blanked out) on
70
+ a straight line between each country's neighbouring years:
71
+
72
+ dftk dataset healthexp -o \\
73
+ | dftk eval -f "le = Life_Expectancy.where(Year % 10 != 5)" -o \\
74
+ | dftk func -c le -t interpolate -g Country --xcol Year -d le_filled
75
+
76
+ The value before instead (last observation carried forward):
77
+
78
+ dftk dataset healthexp -o \\
79
+ | dftk eval -f "le = Life_Expectancy.where(Year % 10 != 5)" -o \\
80
+ | dftk func -c le -t ffill -g Country --xcol Year -d le_filled
81
+
82
+ No gaps left: interpolate, then carry the end values out to the ends:
83
+
84
+ dftk dataset healthexp -o \\
85
+ | dftk eval -f "le = Life_Expectancy.where(Year % 10 != 0)" -o \\
86
+ | dftk func -c le -t interpolate -g Country --xcol Year -d le_filled -o \\
87
+ | dftk func -c le_filled -t ffill -g Country --xcol Year -d le_filled -o \\
88
+ | dftk func -c le_filled -t bfill -g Country --xcol Year -d le_filled
89
+
90
+ Multiple transforms in one call:
91
+
92
+ dftk dataset tips -o | dftk func -c total_bill -t cumsum -d bill_cumsum -o \\
93
+ | dftk func -c total_bill -t mean -g day -d bill_daymean
94
+ """
95
+
96
+ import argparse
97
+ import re
98
+
99
+ import numpy as np
100
+ import pandas as pd
101
+
102
+ from dftk.commands.base import BaseCommand
103
+ from dftk.common.io import check_cols, io
104
+
105
+ # Transforms that use groupby().transform()
106
+ _GROUPBY_TRANSFORMS = {"sum", "mean", "min", "max", "count", "median", "std"}
107
+
108
+ # Transforms that use cumsum / rank within an optional group
109
+ _CUMULATIVE_TRANSFORMS = {"cumsum", "rank", "pct_rank"}
110
+
111
+ # Transforms that fill empty cells, in --xcol order (required)
112
+ _FILL_TRANSFORMS = {"interpolate", "ffill", "bfill"}
113
+
114
+ _VALID = (
115
+ "sum, mean, min, max, count, median, std, cumsum, rank, pct_rank, qcut:N, "
116
+ "interpolate, ffill, bfill"
117
+ )
118
+
119
+
120
+ def _group_indices(df: pd.DataFrame, groupcols: list[str] | None):
121
+ """(group name, row positions) for each group, or one group of all rows."""
122
+ if not groupcols:
123
+ return [(None, np.arange(len(df)))]
124
+ gb = df.groupby(groupcols, sort=False, dropna=False)
125
+ return list(gb.indices.items())
126
+
127
+
128
+ def _group_label(name, groupcols) -> str:
129
+ if not isinstance(name, tuple):
130
+ name = (name,)
131
+ return ", ".join(f"{c}={v}" for c, v in zip(groupcols, name, strict=True))
132
+
133
+
134
+ def _interp_x(x: pd.Series, xcol: str) -> np.ndarray:
135
+ """X as floats for np.interp: numbers as they are, dates as nanoseconds."""
136
+ if pd.api.types.is_bool_dtype(x):
137
+ raise ValueError(f"--xcol {xcol!r} is true/false; interpolate needs numbers.")
138
+ if pd.api.types.is_datetime64_any_dtype(x):
139
+ if getattr(x.dt, "tz", None) is not None:
140
+ x = x.dt.tz_convert("UTC").dt.tz_localize(None)
141
+ ns = x.to_numpy(dtype="datetime64[ns]").astype("int64").astype(float)
142
+ return np.where(x.isna().to_numpy(), np.nan, ns)
143
+ if not pd.api.types.is_numeric_dtype(x):
144
+ raise ValueError(
145
+ f"--xcol {xcol!r} must be numbers or dates for interpolate "
146
+ "(ffill and bfill also take text)."
147
+ )
148
+ return x.to_numpy(dtype=float, na_value=np.nan)
149
+
150
+
151
+ def _sort_key(x: pd.Series) -> np.ndarray:
152
+ """Rank of each X value (ties share one), -1 where X is missing."""
153
+ return pd.factorize(x, sort=True, use_na_sentinel=True)[0]
154
+
155
+
156
+ def _fill_gaps(
157
+ df: pd.DataFrame,
158
+ col: str,
159
+ transform: str,
160
+ groupcols: list[str] | None,
161
+ xcol: str,
162
+ ) -> pd.Series:
163
+ """interpolate / ffill / bfill *col* within groups, in *xcol* order."""
164
+ values = df[col]
165
+
166
+ if transform == "interpolate":
167
+ if pd.api.types.is_bool_dtype(values) or not pd.api.types.is_numeric_dtype(
168
+ values
169
+ ):
170
+ raise ValueError(f"interpolate needs a numeric column; {col!r} is not.")
171
+ xall = _interp_x(df[xcol], xcol)
172
+ v = values.to_numpy(dtype=float, na_value=np.nan)
173
+ out = v.copy()
174
+ for name, idx in _group_indices(df, groupcols):
175
+ x = xall[idx]
176
+ has_x = ~np.isnan(x)
177
+ xs = x[has_x]
178
+ if len(np.unique(xs)) < len(xs):
179
+ where = (
180
+ f" in group {_group_label(name, groupcols)}" if groupcols else ""
181
+ )
182
+ raise ValueError(
183
+ f"Repeated --xcol {xcol!r} values{where}; interpolate needs "
184
+ "one row per X value in each group."
185
+ )
186
+ known = has_x & ~np.isnan(v[idx])
187
+ if known.sum() < 2:
188
+ continue
189
+ kx, kv = x[known], v[idx][known]
190
+ order = np.argsort(kx)
191
+ kx, kv = kx[order], kv[order]
192
+ gap = has_x & np.isnan(v[idx]) & (x > kx[0]) & (x < kx[-1])
193
+ out[idx[gap]] = np.interp(x[gap], kx, kv)
194
+ return pd.Series(out, index=df.index, name=col)
195
+
196
+ # ffill / bfill: lexsort is stable, so rows with the same X keep file order
197
+ key = _sort_key(df[xcol])
198
+ codes = (
199
+ df.groupby(groupcols, sort=False, dropna=False).ngroup().to_numpy()
200
+ if groupcols
201
+ else np.zeros(len(df), dtype=np.int64)
202
+ )
203
+ rows = np.flatnonzero(key >= 0)
204
+ order = rows[np.lexsort((key[rows], codes[rows]))]
205
+ part = values.iloc[order].reset_index(drop=True)
206
+ grouped = part.groupby(codes[order])
207
+ filled = grouped.ffill() if transform == "ffill" else grouped.bfill()
208
+ out = values.copy()
209
+ out.iloc[order] = filled.to_numpy()
210
+ return out
211
+
212
+
213
+ def _apply_transform(
214
+ df: pd.DataFrame,
215
+ col: str,
216
+ transform: str,
217
+ groupcols: list[str] | None,
218
+ destcol: str,
219
+ xcol: str | None = None,
220
+ ) -> pd.DataFrame:
221
+ """Apply *transform* on *col* within optional *groupcols*, storing result in *destcol*.""" # noqa: E501
222
+
223
+ if transform in _FILL_TRANSFORMS:
224
+ if xcol is None:
225
+ raise ValueError(
226
+ f"{transform} needs -x/--xcol: the column that orders each "
227
+ "group's rows (time, position, year, ...)."
228
+ )
229
+ df[destcol] = _fill_gaps(df, col, transform, groupcols, xcol)
230
+ return df
231
+ if xcol is not None:
232
+ raise ValueError("--xcol is only for interpolate, ffill and bfill.")
233
+
234
+ # --- qcut:N ---
235
+ m = re.fullmatch(r"qcut:(\d+)", transform)
236
+ if m:
237
+ n = int(m.group(1))
238
+ if n < 2:
239
+ raise ValueError("qcut requires N >= 2")
240
+ if groupcols:
241
+
242
+ def _qcut_group(s: pd.Series) -> pd.Series:
243
+ return (
244
+ pd.qcut(s, n, labels=False, duplicates="drop").astype("Int64") + 1
245
+ ) # noqa: E501
246
+
247
+ df[destcol] = df.groupby(groupcols)[col].transform(_qcut_group)
248
+ else:
249
+ df[destcol] = (
250
+ pd.qcut(df[col], n, labels=False, duplicates="drop").astype("Int64") + 1
251
+ )
252
+ return df
253
+
254
+ # --- groupby().transform() aggregates ---
255
+ if transform in _GROUPBY_TRANSFORMS:
256
+ if groupcols:
257
+ df[destcol] = df.groupby(groupcols)[col].transform(transform)
258
+ else:
259
+ agg_val = getattr(df[col], transform)()
260
+ df[destcol] = agg_val
261
+ return df
262
+
263
+ # --- cumsum ---
264
+ if transform == "cumsum":
265
+ if groupcols:
266
+ df[destcol] = df.groupby(groupcols)[col].transform("cumsum")
267
+ else:
268
+ df[destcol] = df[col].cumsum()
269
+ return df
270
+
271
+ # --- rank ---
272
+ if transform == "rank":
273
+ if groupcols:
274
+ df[destcol] = df.groupby(groupcols)[col].rank(method="average")
275
+ else:
276
+ df[destcol] = df[col].rank(method="average")
277
+ return df
278
+
279
+ # --- pct_rank ---
280
+ if transform == "pct_rank":
281
+ if groupcols:
282
+ df[destcol] = df.groupby(groupcols)[col].rank(method="average", pct=True)
283
+ else:
284
+ df[destcol] = df[col].rank(method="average", pct=True)
285
+ return df
286
+
287
+ raise ValueError(f"Unknown transform {transform!r}. Valid: {_VALID}")
288
+
289
+
290
+ def _default_destcol(col: str, transform: str) -> str:
291
+ """Generate a destination column name from source column + transform."""
292
+ safe = re.sub(r"[^a-zA-Z0-9_]", "_", transform)
293
+ return f"{col}_{safe}"
294
+
295
+
296
+ class FuncCommand(BaseCommand):
297
+ name = "func"
298
+ help = "Apply column transforms (cumsum, group mean/sum, qcut, interpolate, …)."
299
+
300
+ def add_arguments(self, parser: argparse.ArgumentParser) -> None:
301
+ parser.formatter_class = argparse.RawDescriptionHelpFormatter
302
+ parser.epilog = __doc__
303
+
304
+ self.add_io_arguments(parser)
305
+
306
+ g = parser.add_argument_group("transform options")
307
+ g.add_argument(
308
+ "-c",
309
+ "--col",
310
+ required=True,
311
+ metavar="COL",
312
+ help="Source column to transform.",
313
+ )
314
+ g.add_argument(
315
+ "-t",
316
+ "--transform",
317
+ required=True,
318
+ metavar="TRANSFORM",
319
+ help=(
320
+ "Transform to apply: sum, mean, min, max, count, median, std, "
321
+ "cumsum, rank, pct_rank, qcut:N, interpolate, ffill or bfill."
322
+ ),
323
+ )
324
+ g.add_argument(
325
+ "-d",
326
+ "--destcol",
327
+ default=None,
328
+ metavar="NAME",
329
+ help="Name of the output column (default: <col>_<transform>).",
330
+ )
331
+ g.add_argument(
332
+ "-g",
333
+ "--groupcol",
334
+ nargs="+",
335
+ default=None,
336
+ metavar="COL",
337
+ help="Group by these column(s) before applying the transform.",
338
+ )
339
+ g.add_argument(
340
+ "-x",
341
+ "--xcol",
342
+ default=None,
343
+ metavar="COL",
344
+ help="Required for interpolate, ffill, bfill: take each group's rows "
345
+ "in the order of this column, and interpolate against its values.",
346
+ )
347
+
348
+ def execute(self, args: argparse.Namespace) -> None:
349
+ df = io.read(args)
350
+
351
+ check_cols(df, [args.col], "-c/--col")
352
+ check_cols(df, args.groupcol, "-g/--groupcol")
353
+ xcol = getattr(args, "xcol", None)
354
+ if xcol is not None:
355
+ check_cols(df, [xcol], "-x/--xcol")
356
+
357
+ destcol = args.destcol or _default_destcol(args.col, args.transform)
358
+
359
+ df = _apply_transform(
360
+ df, args.col, args.transform, args.groupcol, destcol, xcol
361
+ )
362
+
363
+ io.printdf(df, args)
@@ -18,7 +18,7 @@ import argparse
18
18
  import numpy as np
19
19
 
20
20
  from dftk.commands.base import BaseCommand
21
- from dftk.common.io import check_cols, io
21
+ from dftk.common.io import check_cols, io, option_columns
22
22
  from dftk.common.plot import (
23
23
  add_figure_arguments,
24
24
  add_group_arguments,
@@ -281,7 +281,7 @@ class HistCommand(BaseCommand):
281
281
  )
282
282
 
283
283
  def execute(self, args: argparse.Namespace) -> None:
284
- df = io.read(args)
284
+ df = io.read(args, columns=option_columns(args))
285
285
  check_cols(df, [args.xcol], "-x/--xcol")
286
286
  check_cols(df, args.groupcol, "-g/--groupcol")
287
287
  check_cols(df, args.subgraphcol, "--subgraphcol")
@@ -20,7 +20,7 @@ import matplotlib.lines as mlines
20
20
  import numpy as np
21
21
 
22
22
  from dftk.commands.base import BaseCommand
23
- from dftk.common.io import check_cols, io
23
+ from dftk.common.io import check_cols, io, option_columns
24
24
  from dftk.common.plot import (
25
25
  add_figure_arguments,
26
26
  add_group_arguments,
@@ -288,7 +288,7 @@ class LineCommand(BaseCommand):
288
288
  if not args.xcol or not args.ycol:
289
289
  raise ValueError("--xcol (-x) and --ycol (-y) are required.")
290
290
 
291
- df = io.read(args)
291
+ df = io.read(args, columns=option_columns(args))
292
292
  check_cols(df, [args.xcol, args.ycol], "-x/-y")
293
293
  check_cols(df, args.groupcol, "-g/--groupcol")
294
294
  check_cols(df, args.subgraphcol, "--subgraphcol")