dataframe-toolkit 0.20.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.20.0 → dataframe_toolkit-0.21.0}/PKG-INFO +19 -14
  2. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/README.md +18 -13
  3. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/eval_cmd.py +4 -2
  6. dataframe_toolkit-0.21.0/src/dftk/commands/func_cmd.py +363 -0
  7. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/skills/dftk/SKILL.md +1 -0
  8. dataframe_toolkit-0.20.0/src/dftk/commands/func_cmd.py +0 -187
  9. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/__init__.py +0 -0
  10. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/cli.py +0 -0
  11. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/__init__.py +0 -0
  12. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/annotate_cmd.py +0 -0
  13. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/append_cmd.py +0 -0
  14. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/base.py +0 -0
  15. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/binx_cmd.py +0 -0
  16. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/chi_cmd.py +0 -0
  17. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/clean_cmd.py +0 -0
  18. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  19. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/concat_cmd.py +0 -0
  20. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/corr_cmd.py +0 -0
  21. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/dataset_cmd.py +0 -0
  22. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/describe_cmd.py +0 -0
  23. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/explode_cmd.py +0 -0
  24. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/fit_cmd.py +0 -0
  25. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/heatmap_cmd.py +0 -0
  26. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/help.py +0 -0
  27. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/hist_cmd.py +0 -0
  28. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/implode_cmd.py +0 -0
  29. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/info_cmd.py +0 -0
  30. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/interp_cmd.py +0 -0
  31. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/line_cmd.py +0 -0
  32. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/manhattan_cmd.py +0 -0
  33. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/melt_cmd.py +0 -0
  34. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/merge_cmd.py +0 -0
  35. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/pairs_cmd.py +0 -0
  36. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/pivot_cmd.py +0 -0
  37. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/print_cmd.py +0 -0
  38. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/qq_cmd.py +0 -0
  39. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/query_cmd.py +0 -0
  40. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/randvar_cmd.py +0 -0
  41. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/sample_cmd.py +0 -0
  42. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/scale_cmd.py +0 -0
  43. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/scat_cmd.py +0 -0
  44. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/segid_cmd.py +0 -0
  45. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/skill_cmd.py +0 -0
  46. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/split_cmd.py +0 -0
  47. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/stat_cmd.py +0 -0
  48. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/test_cmd.py +0 -0
  49. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/transpose_cmd.py +0 -0
  50. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/commands/wstat_cmd.py +0 -0
  51. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/common/__init__.py +0 -0
  52. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/common/copula.py +0 -0
  53. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/common/docformats.py +0 -0
  54. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/common/evalfuncs.py +0 -0
  55. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/common/gwas.py +0 -0
  56. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/common/io.py +0 -0
  57. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/common/plot.py +0 -0
  58. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/common/seed.py +0 -0
  59. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/common/seq.py +0 -0
  60. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/common/stats.py +0 -0
  61. {dataframe_toolkit-0.20.0 → dataframe_toolkit-0.21.0}/src/dftk/io.py +0 -0
  62. {dataframe_toolkit-0.20.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.20.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
@@ -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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dataframe-toolkit"
3
- version = "0.20.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.20.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 = [
@@ -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)
@@ -122,6 +122,7 @@ Transform:
122
122
  | Swap rows and columns | `transpose` |
123
123
  | Rename columns to lowercase identifiers (`Sample ID` → `sample_id`, `GC %` → `gc_pct`) so SQL, `eval` and formulas need no quoting | `cleannames [--mapping FILE]` |
124
124
  | Per-group values broadcast to every row (group mean, rank, cumsum, quantile bin) | `func -c COL -t TRANSFORM -g GROUP` |
125
+ | Fill gaps on a straight line (or with the value before/after) within groups, by an x column for uneven spacing | `func -c COL -t interpolate -g GROUP --xcol X` (`-t ffill`, `-t bfill`) |
125
126
  | Bin a numeric column | `binx -c COL -b 0:100:10` |
126
127
  | Normalise, rank-transform or detrend columns | `scale` |
127
128
  | Look up y at x from a reference curve | `interp DATAFILE --ref CURVE -x X -v Y` |
@@ -1,187 +0,0 @@
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
-
23
- EXAMPLES
24
- --------
25
- Cumulative sum of "value":
26
-
27
- dftk func data.tsv -c value -t cumsum
28
- dftk dataset tips -o | dftk func -c total_bill -t cumsum
29
-
30
- Group mean broadcast (adds "total_bill_mean" unless -d is given):
31
-
32
- dftk dataset tips -o | dftk func -c total_bill -g day -t mean
33
-
34
- Quantile bins (quartiles):
35
-
36
- dftk dataset tips -o | dftk func -c tip -t qcut:4 -d tip_quartile
37
-
38
- Multiple transforms in one call:
39
-
40
- dftk dataset tips -o | dftk func -c total_bill -t cumsum -d bill_cumsum -o \\
41
- | dftk func -c total_bill -t mean -g day -d bill_daymean
42
- """
43
-
44
- import argparse
45
- import re
46
-
47
- import pandas as pd
48
-
49
- from dftk.commands.base import BaseCommand
50
- from dftk.common.io import check_cols, io
51
-
52
- # Transforms that use groupby().transform()
53
- _GROUPBY_TRANSFORMS = {"sum", "mean", "min", "max", "count", "median", "std"}
54
-
55
- # Transforms that use cumsum / rank within an optional group
56
- _CUMULATIVE_TRANSFORMS = {"cumsum", "rank", "pct_rank"}
57
-
58
-
59
- def _apply_transform(
60
- df: pd.DataFrame,
61
- col: str,
62
- transform: str,
63
- groupcols: list[str] | None,
64
- destcol: str,
65
- ) -> pd.DataFrame:
66
- """Apply *transform* on *col* within optional *groupcols*, storing result in *destcol*.""" # noqa: E501
67
-
68
- # --- qcut:N ---
69
- m = re.fullmatch(r"qcut:(\d+)", transform)
70
- if m:
71
- n = int(m.group(1))
72
- if n < 2:
73
- raise ValueError("qcut requires N >= 2")
74
- if groupcols:
75
-
76
- def _qcut_group(s: pd.Series) -> pd.Series:
77
- return (
78
- pd.qcut(s, n, labels=False, duplicates="drop").astype("Int64") + 1
79
- ) # noqa: E501
80
-
81
- df[destcol] = df.groupby(groupcols)[col].transform(_qcut_group)
82
- else:
83
- df[destcol] = (
84
- pd.qcut(df[col], n, labels=False, duplicates="drop").astype("Int64") + 1
85
- )
86
- return df
87
-
88
- # --- groupby().transform() aggregates ---
89
- if transform in _GROUPBY_TRANSFORMS:
90
- if groupcols:
91
- df[destcol] = df.groupby(groupcols)[col].transform(transform)
92
- else:
93
- agg_val = getattr(df[col], transform)()
94
- df[destcol] = agg_val
95
- return df
96
-
97
- # --- cumsum ---
98
- if transform == "cumsum":
99
- if groupcols:
100
- df[destcol] = df.groupby(groupcols)[col].transform("cumsum")
101
- else:
102
- df[destcol] = df[col].cumsum()
103
- return df
104
-
105
- # --- rank ---
106
- if transform == "rank":
107
- if groupcols:
108
- df[destcol] = df.groupby(groupcols)[col].rank(method="average")
109
- else:
110
- df[destcol] = df[col].rank(method="average")
111
- return df
112
-
113
- # --- pct_rank ---
114
- if transform == "pct_rank":
115
- if groupcols:
116
- df[destcol] = df.groupby(groupcols)[col].rank(method="average", pct=True)
117
- else:
118
- df[destcol] = df[col].rank(method="average", pct=True)
119
- return df
120
-
121
- raise ValueError(
122
- f"Unknown transform {transform!r}. "
123
- "Valid: sum, mean, min, max, count, median, std, cumsum, rank, pct_rank, qcut:N"
124
- )
125
-
126
-
127
- def _default_destcol(col: str, transform: str) -> str:
128
- """Generate a destination column name from source column + transform."""
129
- safe = re.sub(r"[^a-zA-Z0-9_]", "_", transform)
130
- return f"{col}_{safe}"
131
-
132
-
133
- class FuncCommand(BaseCommand):
134
- name = "func"
135
- help = "Apply column transforms (cumsum, group mean/sum, qcut, …)."
136
-
137
- def add_arguments(self, parser: argparse.ArgumentParser) -> None:
138
- parser.formatter_class = argparse.RawDescriptionHelpFormatter
139
- parser.epilog = __doc__
140
-
141
- self.add_io_arguments(parser)
142
-
143
- g = parser.add_argument_group("transform options")
144
- g.add_argument(
145
- "-c",
146
- "--col",
147
- required=True,
148
- metavar="COL",
149
- help="Source column to transform.",
150
- )
151
- g.add_argument(
152
- "-t",
153
- "--transform",
154
- required=True,
155
- metavar="TRANSFORM",
156
- help=(
157
- "Transform to apply: sum, mean, min, max, count, median, std, "
158
- "cumsum, rank, pct_rank, or qcut:N."
159
- ),
160
- )
161
- g.add_argument(
162
- "-d",
163
- "--destcol",
164
- default=None,
165
- metavar="NAME",
166
- help="Name of the output column (default: <col>_<transform>).",
167
- )
168
- g.add_argument(
169
- "-g",
170
- "--groupcol",
171
- nargs="+",
172
- default=None,
173
- metavar="COL",
174
- help="Group by these column(s) before applying the transform.",
175
- )
176
-
177
- def execute(self, args: argparse.Namespace) -> None:
178
- df = io.read(args)
179
-
180
- check_cols(df, [args.col], "-c/--col")
181
- check_cols(df, args.groupcol, "-g/--groupcol")
182
-
183
- destcol = args.destcol or _default_destcol(args.col, args.transform)
184
-
185
- df = _apply_transform(df, args.col, args.transform, args.groupcol, destcol)
186
-
187
- io.printdf(df, args)