dataframe-toolkit 0.20.0__tar.gz → 0.22.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.20.0 → dataframe_toolkit-0.22.0}/PKG-INFO +27 -14
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/README.md +26 -13
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/pyproject.toml +1 -1
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/pyproject.toml.orig +1 -1
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/__init__.py +1 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/eval_cmd.py +4 -2
- dataframe_toolkit-0.22.0/src/dftk/commands/func_cmd.py +363 -0
- dataframe_toolkit-0.22.0/src/dftk/commands/locus_cmd.py +430 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/manhattan_cmd.py +4 -2
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/skills/dftk/SKILL.md +4 -1
- dataframe_toolkit-0.20.0/src/dftk/commands/func_cmd.py +0 -187
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/__init__.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/cli.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/annotate_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/append_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/base.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/binx_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/chi_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/clean_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/cleannames_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/concat_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/corr_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/dataset_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/describe_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/explode_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/fit_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/heatmap_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/help.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/hist_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/implode_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/info_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/interp_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/line_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/melt_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/merge_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/pairs_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/pivot_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/print_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/qq_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/query_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/randvar_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/sample_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/scale_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/scat_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/segid_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/skill_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/split_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/stat_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/test_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/transpose_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/commands/wstat_cmd.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/common/__init__.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/common/copula.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/common/docformats.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/common/evalfuncs.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/common/gwas.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/common/io.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/common/plot.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/common/seed.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/common/seq.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/common/stats.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.0}/src/dftk/io.py +0 -0
- {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.22.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.22.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 |
|
|
@@ -168,6 +168,7 @@ publication-quality output.
|
|
|
168
168
|
| `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
|
|
169
169
|
| `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
|
|
170
170
|
| `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
|
|
171
|
+
| `locus` | Regional association plot: -log10(p) in one region coloured by r² with the lead variant (`--ldcol`), lead as a diamond, `--lead`/`--label` by ID or `chr:pos` |
|
|
171
172
|
| `manhattan` | Genome-wide -log10(p) by position (`Chr`, `pos`, `Pval`, or `--mlogpcol`/`--chi2col`); significance lines, thinning for millions of variants, `-g`/`--subgraphcol` for several scans |
|
|
172
173
|
|
|
173
174
|
### Utilities
|
|
@@ -345,8 +346,9 @@ dftk dataset co2 -o | dftk eval -f "ffill = co2.ffill()" \
|
|
|
345
346
|
|
|
346
347
|
`ffill` leaves the first rows empty and `bfill` the last ones;
|
|
347
348
|
`x.ffill().fillna(x.bfill())` fills both. `interpolate()` counts one step
|
|
348
|
-
per row, so the rows must be evenly spaced; for
|
|
349
|
-
|
|
349
|
+
per row, so the rows must be evenly spaced; for unevenly spaced rows use
|
|
350
|
+
`func -t interpolate --xcol X` (below), and for a lookup from a reference
|
|
351
|
+
curve, `dftk interp`.
|
|
350
352
|
|
|
351
353
|
**Row order and groups.** These methods use the rows in the order they are
|
|
352
354
|
in. Sort first, in a step of its own: `--sortasc` applies to a command's
|
|
@@ -362,21 +364,25 @@ dftk dataset healthexp -o \
|
|
|
362
364
|
| dftk eval -f "le_filled = le.groupby(Country).ffill()"
|
|
363
365
|
```
|
|
364
366
|
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
367
|
+
For interpolation within groups, `func -t interpolate` does it in one
|
|
368
|
+
step. It draws the line against an x column (`--xcol`, required), so
|
|
369
|
+
unevenly spaced rows (missing years, genome positions) get the right
|
|
370
|
+
values; it takes each group's rows in X order itself, so no sort step is
|
|
371
|
+
needed, and it leaves gaps before a group's first value or after its last
|
|
372
|
+
empty. `-t ffill` and `-t bfill` work the same way; chained after
|
|
373
|
+
`interpolate` on the same column (`-d`), they fill those ends too:
|
|
369
374
|
|
|
370
375
|
```bash
|
|
371
376
|
dftk dataset healthexp -o \
|
|
372
|
-
| dftk eval -f "le = Life_Expectancy.where(Year % 10 != 5)" \
|
|
373
|
-
|
|
374
|
-
| dftk
|
|
375
|
-
|
|
376
|
-
-f "le_linear = le.interpolate().where(before & after)" \
|
|
377
|
-
--drop before after
|
|
377
|
+
| dftk eval -f "le = Life_Expectancy.where(Year % 10 != 5)" -o \
|
|
378
|
+
| dftk func -c le -t interpolate -g Country --xcol Year -d le_filled -o \
|
|
379
|
+
| dftk func -c le_filled -t ffill -g Country --xcol Year -d le_filled -o \
|
|
380
|
+
| dftk func -c le_filled -t bfill -g Country --xcol Year -d le_filled
|
|
378
381
|
```
|
|
379
382
|
|
|
383
|
+
`eval`'s `interpolate()` counts one step per row: with 10 at x=2 and 14 at
|
|
384
|
+
x=6, it gives the gap at x=5 12.0, where `func --xcol` gives 13.0.
|
|
385
|
+
|
|
380
386
|
### Differences between rows
|
|
381
387
|
|
|
382
388
|
For the change in a column from one row to the next, `eval -f` takes
|
|
@@ -504,6 +510,13 @@ dftk dataset gwas -o | dftk eval -f "Chisq = Chisq * 1.15" -o | dftk qq --chi2co
|
|
|
504
510
|
|
|
505
511
|
`qq --logy` makes its y axis linear up to 10 and logarithmic above, as in `manhattan`.
|
|
506
512
|
|
|
513
|
+
`locus` zooms in on one region: -log10(p) against position in Mb, the points coloured by r² with the lead variant (`--ldcol`, five bins, grey where missing) and the lead drawn as a diamond. It plots the rows it gets, so cut the region out with `query` first (input on several chromosomes is an error that suggests a query around the top hit). The lead is the smallest p-value unless `--lead` names one, and `--label` names more variants to write on the plot; both take an ID (`SNP` column, or `--idcol`) or a position like `chr6:32600000`. dftk doesn't compute LD: merge in r² with the lead, e.g. from `plink --r2 --ld-snp`. `dataset gwas` has an `r2` column around each peak:
|
|
514
|
+
|
|
515
|
+
```bash
|
|
516
|
+
dftk dataset gwas -o | dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6e6" -o \
|
|
517
|
+
| dftk locus --ldcol r2 -f locus.png
|
|
518
|
+
```
|
|
519
|
+
|
|
507
520
|
### Bootstrap confidence intervals
|
|
508
521
|
|
|
509
522
|
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 |
|
|
@@ -138,6 +138,7 @@ publication-quality output.
|
|
|
138
138
|
| `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
|
|
139
139
|
| `pairs` | Scatter-plot matrix with KDEs (or histograms) on the diagonal; `-g` colours groups, `--upper corr` puts r in the upper triangle |
|
|
140
140
|
| `qq` | QQ plot of p-values: observed against expected -log10(p), confidence band, genomic inflation λ; `-g` one curve and λ per group |
|
|
141
|
+
| `locus` | Regional association plot: -log10(p) in one region coloured by r² with the lead variant (`--ldcol`), lead as a diamond, `--lead`/`--label` by ID or `chr:pos` |
|
|
141
142
|
| `manhattan` | Genome-wide -log10(p) by position (`Chr`, `pos`, `Pval`, or `--mlogpcol`/`--chi2col`); significance lines, thinning for millions of variants, `-g`/`--subgraphcol` for several scans |
|
|
142
143
|
|
|
143
144
|
### Utilities
|
|
@@ -315,8 +316,9 @@ dftk dataset co2 -o | dftk eval -f "ffill = co2.ffill()" \
|
|
|
315
316
|
|
|
316
317
|
`ffill` leaves the first rows empty and `bfill` the last ones;
|
|
317
318
|
`x.ffill().fillna(x.bfill())` fills both. `interpolate()` counts one step
|
|
318
|
-
per row, so the rows must be evenly spaced; for
|
|
319
|
-
|
|
319
|
+
per row, so the rows must be evenly spaced; for unevenly spaced rows use
|
|
320
|
+
`func -t interpolate --xcol X` (below), and for a lookup from a reference
|
|
321
|
+
curve, `dftk interp`.
|
|
320
322
|
|
|
321
323
|
**Row order and groups.** These methods use the rows in the order they are
|
|
322
324
|
in. Sort first, in a step of its own: `--sortasc` applies to a command's
|
|
@@ -332,21 +334,25 @@ dftk dataset healthexp -o \
|
|
|
332
334
|
| dftk eval -f "le_filled = le.groupby(Country).ffill()"
|
|
333
335
|
```
|
|
334
336
|
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
337
|
+
For interpolation within groups, `func -t interpolate` does it in one
|
|
338
|
+
step. It draws the line against an x column (`--xcol`, required), so
|
|
339
|
+
unevenly spaced rows (missing years, genome positions) get the right
|
|
340
|
+
values; it takes each group's rows in X order itself, so no sort step is
|
|
341
|
+
needed, and it leaves gaps before a group's first value or after its last
|
|
342
|
+
empty. `-t ffill` and `-t bfill` work the same way; chained after
|
|
343
|
+
`interpolate` on the same column (`-d`), they fill those ends too:
|
|
339
344
|
|
|
340
345
|
```bash
|
|
341
346
|
dftk dataset healthexp -o \
|
|
342
|
-
| dftk eval -f "le = Life_Expectancy.where(Year % 10 != 5)" \
|
|
343
|
-
|
|
344
|
-
| dftk
|
|
345
|
-
|
|
346
|
-
-f "le_linear = le.interpolate().where(before & after)" \
|
|
347
|
-
--drop before after
|
|
347
|
+
| dftk eval -f "le = Life_Expectancy.where(Year % 10 != 5)" -o \
|
|
348
|
+
| dftk func -c le -t interpolate -g Country --xcol Year -d le_filled -o \
|
|
349
|
+
| dftk func -c le_filled -t ffill -g Country --xcol Year -d le_filled -o \
|
|
350
|
+
| dftk func -c le_filled -t bfill -g Country --xcol Year -d le_filled
|
|
348
351
|
```
|
|
349
352
|
|
|
353
|
+
`eval`'s `interpolate()` counts one step per row: with 10 at x=2 and 14 at
|
|
354
|
+
x=6, it gives the gap at x=5 12.0, where `func --xcol` gives 13.0.
|
|
355
|
+
|
|
350
356
|
### Differences between rows
|
|
351
357
|
|
|
352
358
|
For the change in a column from one row to the next, `eval -f` takes
|
|
@@ -474,6 +480,13 @@ dftk dataset gwas -o | dftk eval -f "Chisq = Chisq * 1.15" -o | dftk qq --chi2co
|
|
|
474
480
|
|
|
475
481
|
`qq --logy` makes its y axis linear up to 10 and logarithmic above, as in `manhattan`.
|
|
476
482
|
|
|
483
|
+
`locus` zooms in on one region: -log10(p) against position in Mb, the points coloured by r² with the lead variant (`--ldcol`, five bins, grey where missing) and the lead drawn as a diamond. It plots the rows it gets, so cut the region out with `query` first (input on several chromosomes is an error that suggests a query around the top hit). The lead is the smallest p-value unless `--lead` names one, and `--label` names more variants to write on the plot; both take an ID (`SNP` column, or `--idcol`) or a position like `chr6:32600000`. dftk doesn't compute LD: merge in r² with the lead, e.g. from `plink --r2 --ld-snp`. `dataset gwas` has an `r2` column around each peak:
|
|
484
|
+
|
|
485
|
+
```bash
|
|
486
|
+
dftk dataset gwas -o | dftk query -q "Chr == '6' and pos > 31.6e6 and pos < 33.6e6" -o \
|
|
487
|
+
| dftk locus --ldcol r2 -f locus.png
|
|
488
|
+
```
|
|
489
|
+
|
|
477
490
|
### Bootstrap confidence intervals
|
|
478
491
|
|
|
479
492
|
Bootstrap mode repeats the full stat computation N times on resampled data
|
|
@@ -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
|
|
73
|
-
|
|
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)
|