dataframe-toolkit 0.28.0__tar.gz → 0.29.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 (65) hide show
  1. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/PKG-INFO +2 -2
  2. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/README.md +1 -1
  3. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/pyproject.toml +1 -1
  4. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/pyproject.toml.orig +1 -1
  5. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/line_cmd.py +3 -1
  6. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/scat_cmd.py +9 -1
  7. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/common/io.py +107 -44
  8. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/common/plot.py +81 -2
  9. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/skills/dftk/SKILL.md +13 -2
  10. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/__init__.py +0 -0
  11. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/cli.py +0 -0
  12. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/__init__.py +0 -0
  13. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/annotate_cmd.py +0 -0
  14. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/append_cmd.py +0 -0
  15. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/base.py +0 -0
  16. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/binx_cmd.py +0 -0
  17. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/box_cmd.py +0 -0
  18. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/chi_cmd.py +0 -0
  19. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/clean_cmd.py +0 -0
  20. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/cleannames_cmd.py +0 -0
  21. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/concat_cmd.py +0 -0
  22. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/corr_cmd.py +0 -0
  23. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/dataset_cmd.py +0 -0
  24. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/describe_cmd.py +0 -0
  25. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/eval_cmd.py +0 -0
  26. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/explode_cmd.py +0 -0
  27. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/fit_cmd.py +0 -0
  28. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/forest_cmd.py +0 -0
  29. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/func_cmd.py +0 -0
  30. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/heatmap_cmd.py +0 -0
  31. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/help.py +0 -0
  32. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/hist_cmd.py +0 -0
  33. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/implode_cmd.py +0 -0
  34. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/info_cmd.py +0 -0
  35. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/interp_cmd.py +0 -0
  36. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/locus_cmd.py +0 -0
  37. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/manhattan_cmd.py +0 -0
  38. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/melt_cmd.py +0 -0
  39. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/merge_cmd.py +0 -0
  40. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/pairs_cmd.py +0 -0
  41. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/phewas_cmd.py +0 -0
  42. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/pivot_cmd.py +0 -0
  43. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/print_cmd.py +0 -0
  44. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/qq_cmd.py +0 -0
  45. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/query_cmd.py +0 -0
  46. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/randvar_cmd.py +0 -0
  47. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/sample_cmd.py +0 -0
  48. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/scale_cmd.py +0 -0
  49. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/segid_cmd.py +0 -0
  50. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/skill_cmd.py +0 -0
  51. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/split_cmd.py +0 -0
  52. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/stat_cmd.py +0 -0
  53. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/test_cmd.py +0 -0
  54. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/transpose_cmd.py +0 -0
  55. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/commands/wstat_cmd.py +0 -0
  56. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/common/__init__.py +0 -0
  57. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/common/copula.py +0 -0
  58. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/common/docformats.py +0 -0
  59. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/common/evalfuncs.py +0 -0
  60. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/common/gwas.py +0 -0
  61. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/common/seed.py +0 -0
  62. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/common/seq.py +0 -0
  63. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/common/stats.py +0 -0
  64. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.0}/src/dftk/io.py +0 -0
  65. {dataframe_toolkit-0.28.0 → dataframe_toolkit-0.29.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.28.0
3
+ Version: 0.29.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
@@ -174,7 +174,7 @@ publication-quality output.
174
174
  | `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` |
175
175
  | `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 |
176
176
 
177
- `scat`, `line` and `hist` draw dashed reference lines with `--vline X` and `--hline Y`, each labelled when written `X:LABEL` (`--vline 412:carriers`); `forest` takes `--vline` and `box` `--hline`.
177
+ `scat`, `line` and `hist` draw dashed reference lines with `--vline X` and `--hline Y`, each labelled when written `X:LABEL` (`--vline 412:carriers`); `forest` takes `--vline` and `box` `--hline`. `scat` and `line` also draw sloped lines y = A + B*x with `--abline A:B[:LABEL]` (intercept, then slope, as in R; `--abline 0:0.15:15%`), across the whole panel without changing its limits; a bare `--abline` is the identity line y = x, and a negative intercept is written `--abline=-1:2`. On log axes the line is drawn as the curve it is. With `--subgraphcol` the same lines go on every panel.
178
178
 
179
179
  ### Utilities
180
180
 
@@ -144,7 +144,7 @@ publication-quality output.
144
144
  | `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` |
145
145
  | `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 |
146
146
 
147
- `scat`, `line` and `hist` draw dashed reference lines with `--vline X` and `--hline Y`, each labelled when written `X:LABEL` (`--vline 412:carriers`); `forest` takes `--vline` and `box` `--hline`.
147
+ `scat`, `line` and `hist` draw dashed reference lines with `--vline X` and `--hline Y`, each labelled when written `X:LABEL` (`--vline 412:carriers`); `forest` takes `--vline` and `box` `--hline`. `scat` and `line` also draw sloped lines y = A + B*x with `--abline A:B[:LABEL]` (intercept, then slope, as in R; `--abline 0:0.15:15%`), across the whole panel without changing its limits; a bare `--abline` is the identity line y = x, and a negative intercept is written `--abline=-1:2`. On log axes the line is drawn as the curve it is. With `--subgraphcol` the same lines go on every panel.
148
148
 
149
149
  ### Utilities
150
150
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "dataframe-toolkit"
3
- version = "0.28.0"
3
+ version = "0.29.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.28.0"
3
+ version = "0.29.0"
4
4
  description = "A command-line toolkit for DataFrame analysis and manipulation"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -27,6 +27,7 @@ from dftk.common.plot import (
27
27
  add_legend_arguments,
28
28
  add_refline_arguments,
29
29
  add_xy_arguments,
30
+ apply_ablines,
30
31
  apply_labels,
31
32
  apply_limits,
32
33
  apply_reflines,
@@ -166,6 +167,7 @@ def _line_ax(ax, df, args, title_suffix: str = ""):
166
167
 
167
168
  apply_reflines(ax, args)
168
169
  apply_limits(ax, args)
170
+ apply_ablines(ax, args)
169
171
  apply_ticks(ax, args)
170
172
  apply_labels(ax, args, default_xlabel=xcol or "", default_ylabel=ycol or "")
171
173
  if title_suffix:
@@ -255,7 +257,7 @@ class LineCommand(BaseCommand):
255
257
  self.add_read_arguments(parser)
256
258
  add_xy_arguments(parser)
257
259
  add_figure_arguments(parser)
258
- add_refline_arguments(parser)
260
+ add_refline_arguments(parser, sloped=True)
259
261
  add_group_arguments(parser)
260
262
  add_legend_arguments(parser)
261
263
 
@@ -32,6 +32,7 @@ from dftk.common.plot import (
32
32
  add_legend_arguments,
33
33
  add_refline_arguments,
34
34
  add_xy_arguments,
35
+ apply_ablines,
35
36
  apply_labels,
36
37
  apply_limits,
37
38
  apply_reflines,
@@ -283,6 +284,7 @@ def _scatter_ax(ax, df, args, title_suffix: str = ""):
283
284
 
284
285
  apply_reflines(ax, args)
285
286
  apply_limits(ax, args)
287
+ apply_ablines(ax, args)
286
288
  apply_ticks(ax, args)
287
289
  apply_labels(ax, args, default_xlabel=xcol or "", default_ylabel=ycol or "")
288
290
  if title_suffix:
@@ -324,6 +326,12 @@ can overshoot the data; a larger --frac or --xlim helps:
324
326
 
325
327
  dftk dataset tips -o | dftk scat -x total_bill -y tip --fit lowess
326
328
 
329
+ Lines y = A + B*x, here 15 % and 20 % tips, on every panel (bare --abline
330
+ is y = x; a negative intercept is written --abline=-1:2):
331
+
332
+ dftk dataset tips -o | dftk scat -x total_bill -y tip --subgraphcol time \\
333
+ --abline 0:0.15:15% 0:0.2:20%
334
+
327
335
  Hexagonal binning for large tables (54,000 diamonds), log colour scale and
328
336
  log axes; hexagons are binned on the log scale:
329
337
 
@@ -386,7 +394,7 @@ class ScatCommand(BaseCommand):
386
394
  self.add_read_arguments(parser)
387
395
  add_xy_arguments(parser)
388
396
  add_figure_arguments(parser)
389
- add_refline_arguments(parser)
397
+ add_refline_arguments(parser, sloped=True)
390
398
  add_group_arguments(parser)
391
399
  add_legend_arguments(parser)
392
400
 
@@ -66,8 +66,93 @@ _CAST_TYPES: dict[str, object] = {
66
66
  "bool": "bool",
67
67
  "datetime64": "datetime64[ns]",
68
68
  "category": "category",
69
+ "str": "string",
70
+ "string": "string",
69
71
  }
70
72
 
73
+
74
+ def _query(df: pd.DataFrame, query: str, option: str) -> pd.DataFrame:
75
+ """df.query for --prequery / --postquery; a bad expression is an input
76
+ error (pandas raises UndefinedVariableError, SyntaxError, ...)."""
77
+ try:
78
+ return df.query(query)
79
+ except Exception as exc:
80
+ raise ValueError(f"{option} {query!r}: {exc}") from None
81
+
82
+
83
+ def _round(df: pd.DataFrame, item: str) -> pd.DataFrame:
84
+ """Apply one --round COL:N (a glob rounds the numeric columns it matches)
85
+ or --round N (every float column). A malformed item, a literal column that
86
+ matches nothing or isn't numeric is an input error."""
87
+ col, sep, n = item.rpartition(":")
88
+ try:
89
+ ndigits = int(n)
90
+ except ValueError:
91
+ raise ValueError(f"--round expects COL:N or N, got {item!r}") from None
92
+ if not sep:
93
+ columns = [c for c in df.columns if df[c].dtype == np.float64]
94
+ elif not col:
95
+ raise ValueError(f"--round expects COL:N or N, got {item!r}")
96
+ elif frozenset("*?[") & set(col):
97
+ columns = [
98
+ c
99
+ for c in fnmatch.filter(df.columns, col)
100
+ if pd.api.types.is_numeric_dtype(df[c])
101
+ and not pd.api.types.is_bool_dtype(df[c])
102
+ ]
103
+ elif col not in df.columns:
104
+ raise ValueError(
105
+ f"--round {item!r}: no column {col!r} (available: {list(df.columns)})"
106
+ )
107
+ elif not pd.api.types.is_numeric_dtype(df[col]):
108
+ raise ValueError(f"--round {item!r}: {col} is not numeric ({df[col].dtype})")
109
+ else:
110
+ columns = [col]
111
+ for c in columns:
112
+ df[c] = df[c].round(ndigits)
113
+ return df
114
+
115
+
116
+ def _cast(df: pd.DataFrame, item: str) -> pd.DataFrame:
117
+ """Apply one --cast COL:TYPE. An unknown type, a literal column name that
118
+ matches nothing or a failed conversion is an input error."""
119
+ col, sep, coltype = item.rpartition(":")
120
+ if not sep or not col or not coltype:
121
+ raise ValueError(f"--cast expects COL:TYPE, got {item!r}")
122
+ # Case-sensitive: "int" is int64, "Int" is the nullable Int64
123
+ matches = [t for t in _CAST_TYPES if fnmatch.fnmatchcase(t, f"{coltype}*")]
124
+ if not matches:
125
+ raise ValueError(
126
+ f"--cast {item!r}: unknown type {coltype!r} "
127
+ f"(choose from {', '.join(_CAST_TYPES)})"
128
+ )
129
+ dtype = _CAST_TYPES[matches[0]]
130
+ columns = fnmatch.filter(df.columns, col)
131
+ if dtype in ("int64", "Int64"):
132
+ for c in columns:
133
+ if pd.api.types.is_float_dtype(df[c]):
134
+ values = df[c].dropna()
135
+ broken = values[values % 1 != 0]
136
+ if len(broken):
137
+ raise ValueError(
138
+ f"--cast {c}:{coltype}: {c} has non-whole numbers "
139
+ f"(e.g. {broken.iloc[0]}); use --round {c}:0 first"
140
+ )
141
+ if not columns and not (frozenset("*?[") & set(col)):
142
+ raise ValueError(
143
+ f"--cast {item!r}: no column {col!r} (available: {list(df.columns)})"
144
+ )
145
+ for c in columns:
146
+ try:
147
+ df[c] = df[c].astype(dtype)
148
+ except Exception as exc:
149
+ try: # e.g. "1.0" text to int: via float
150
+ df[c] = df[c].astype(float).astype(dtype)
151
+ except Exception:
152
+ raise ValueError(f"--cast {c}:{coltype}: {exc}") from None
153
+ return df
154
+
155
+
71
156
  DFTK_TMPDIR: str = os.environ.get(
72
157
  "DFTK_TMPDIR",
73
158
  os.path.join(tempfile.gettempdir(), "dftk"),
@@ -544,11 +629,7 @@ class io:
544
629
  # -- prequery ------------------------------------------------------
545
630
 
546
631
  for query in prequery:
547
- try:
548
- df = df.query(query)
549
- except Exception as exc:
550
- logging.error(f"--prequery failed ({query!r}): {exc}")
551
- raise
632
+ df = _query(df, query, "--prequery")
552
633
 
553
634
  return df
554
635
 
@@ -640,9 +721,12 @@ class io:
640
721
  "--cast",
641
722
  help=(
642
723
  "Cast column to dtype (COL:TYPE). TYPE is one of object, int64, "
643
- "Int64, float64, bool, datetime64, category (a prefix is enough, "
644
- "e.g. int, Int, cat). Int64 is an integer column that allows "
645
- "empty cells. Glob patterns supported."
724
+ "Int64, float64, bool, datetime64, category, str (a prefix is "
725
+ "enough, e.g. int, Int, cat). Int64 is an integer column that "
726
+ "allows empty cells; str is text (written to parquet as a "
727
+ "string column; empty cells stay empty). Casts apply in "
728
+ "order, so --cast c:Int64 c:str turns 1.0 into 1. Glob "
729
+ "patterns supported; a type that doesn't fit is an error."
646
730
  ),
647
731
  nargs="*",
648
732
  default=None,
@@ -651,8 +735,11 @@ class io:
651
735
  g.add_argument(
652
736
  "--round",
653
737
  help=(
654
- "Round columns to N decimal places (COL:N). "
655
- "A bare integer N rounds all float columns."
738
+ "Round columns to N decimal places (COL:N; a glob rounds "
739
+ "the numeric columns it matches). A bare integer N rounds all "
740
+ "float columns. Done before --cast, so --round x:0 --cast "
741
+ "x:int gives the nearest integer (halves go to the even "
742
+ "number: 2.5 to 2, 3.5 to 4)."
656
743
  ),
657
744
  nargs="*",
658
745
  default=None,
@@ -735,7 +822,9 @@ class io:
735
822
  help=(
736
823
  "Drop rows containing any NA value from the output. Applied "
737
824
  "after the command has run, so it does not change what the "
738
- "command sees (use --prequery for that)."
825
+ "command sees (use --prequery for that). For one column: "
826
+ "--postquery 'COL.notna()'; for 2 or missing: --postquery "
827
+ "'b == 2 or b.isna()' (b == 2 alone drops the missing rows)."
739
828
  ),
740
829
  action="store_true",
741
830
  )
@@ -789,27 +878,16 @@ class io:
789
878
 
790
879
  # Post-query filter
791
880
  for query in getattr(args, "postquery", []):
792
- try:
793
- df = df.query(query)
794
- except Exception as exc:
795
- logging.error(f"--postquery failed ({query!r}): {exc}")
796
- raise
881
+ df = _query(df, query, "--postquery")
882
+
883
+ # Round decimal places; before --cast, so --round x:0 --cast x:int
884
+ # gives the nearest integer
885
+ for item in getattr(args, "round", None) or []:
886
+ df = _round(df, item)
797
887
 
798
888
  # Cast columns
799
889
  for item in getattr(args, "cast", None) or []:
800
- try:
801
- col, coltype = item.split(":")
802
- # Case-sensitive: "int" is int64, "Int" is the nullable Int64
803
- pattern = f"{coltype}*"
804
- matches = [t for t in _CAST_TYPES if fnmatch.fnmatchcase(t, pattern)]
805
- dtype = _CAST_TYPES[matches[0]]
806
- for c in fnmatch.filter(df.columns, col):
807
- try:
808
- df[c] = df[c].astype(dtype)
809
- except Exception:
810
- df[c] = df[c].astype(float).astype(dtype)
811
- except Exception:
812
- logging.warning(f"--cast: failed for {item!r}")
890
+ df = _cast(df, item)
813
891
 
814
892
  # Sort; --sortasc or --sortdesc without names sorts by every column,
815
893
  # left to right
@@ -888,21 +966,6 @@ class io:
888
966
  except Exception as exc:
889
967
  logging.error(f"--select failed: {exc}")
890
968
 
891
- # Round decimal places
892
- for item in getattr(args, "round", None) or []:
893
- try:
894
- col, n = item.split(":")
895
- for c in fnmatch.filter(df.columns, col):
896
- df[c] = df[c].round(int(n))
897
- except Exception:
898
- try:
899
- n = int(item)
900
- for c in df.columns:
901
- if df[c].dtype == np.float64:
902
- df[c] = df[c].round(n)
903
- except Exception:
904
- pass
905
-
906
969
  # Deduplicate
907
970
  dedup = getattr(args, "deduplicate", None)
908
971
  if dedup is not None:
@@ -418,11 +418,90 @@ def apply_reflines(ax: matplotlib.axes.Axes, args: argparse.Namespace) -> None:
418
418
  )
419
419
 
420
420
 
421
+ def abline(value: str) -> tuple[float, float, str | None]:
422
+ """--abline value: INTERCEPT:SLOPE, or INTERCEPT:SLOPE:LABEL."""
423
+ a, sep, rest = value.partition(":")
424
+ b, _, label = rest.partition(":")
425
+ try:
426
+ if not sep:
427
+ raise ValueError
428
+ return float(a), float(b), (label or None)
429
+ except ValueError:
430
+ raise argparse.ArgumentTypeError(
431
+ f"expected INTERCEPT:SLOPE[:LABEL], not {value!r}"
432
+ ) from None
433
+
434
+
435
+ class _AblineAction(argparse.Action):
436
+ """--abline may be given more than once (a negative intercept needs
437
+ --abline=-1:2, one line per option); bare --abline adds y = x."""
438
+
439
+ def __call__(self, parser, namespace, values, option_string=None):
440
+ lines = list(getattr(namespace, self.dest, None) or [])
441
+ lines += values or [(0.0, 1.0, None)]
442
+ setattr(namespace, self.dest, lines)
443
+
444
+
445
+ def apply_ablines(ax: matplotlib.axes.Axes, args: argparse.Namespace) -> None:
446
+ """Draw --abline lines y = a + b*x across the whole panel, in the style of
447
+ --vline / --hline. Call after apply_limits: the line is drawn over the
448
+ final x range and leaves the limits as they are, so it never zooms the
449
+ plot out. On a log axis the line is a curve, drawn point by point."""
450
+ lines = getattr(args, "abline", None)
451
+ if not lines:
452
+ return
453
+ import numpy as np
454
+
455
+ xlim, ylim = ax.get_xlim(), ax.get_ylim()
456
+ logx = ax.get_xscale() == "log"
457
+ x = np.geomspace(*xlim, 512) if logx else np.linspace(*xlim, 512)
458
+ lo, hi = sorted(ylim)
459
+ for a, b, label in lines:
460
+ y = a + b * x
461
+ ax.plot(x, y, color=_REFLINE_COLOUR, ls="--", lw=0.9, zorder=1.5)
462
+ if label:
463
+ # at the right-most point inside the panel, along the line
464
+ inside = np.flatnonzero((y > lo) & (y < hi))
465
+ if len(inside):
466
+ i = max(inside[0], inside[-1] - 10)
467
+ ax.text(
468
+ x[i],
469
+ y[i],
470
+ f"{label} ",
471
+ ha="right",
472
+ va="bottom",
473
+ fontsize="small",
474
+ color=_REFLINE_COLOUR,
475
+ rotation=float(np.degrees(np.arctan(b))),
476
+ rotation_mode="anchor",
477
+ transform_rotates_text=True,
478
+ )
479
+ ax.set_xlim(xlim)
480
+ ax.set_ylim(ylim)
481
+
482
+
421
483
  def add_refline_arguments(
422
- parser: argparse.ArgumentParser, vertical: bool = True, horizontal: bool = True
484
+ parser: argparse.ArgumentParser,
485
+ vertical: bool = True,
486
+ horizontal: bool = True,
487
+ sloped: bool = False,
423
488
  ) -> None:
424
- """Add --vline / --hline (reference lines with optional labels)."""
489
+ """Add --vline / --hline (reference lines with optional labels), and
490
+ --abline with *sloped* (plots with a numeric x and y: scat, line)."""
425
491
  g = parser.add_argument_group("reference lines")
492
+ if sloped:
493
+ g.add_argument(
494
+ "--abline",
495
+ nargs="*",
496
+ type=abline,
497
+ action=_AblineAction,
498
+ default=None,
499
+ metavar="A:B[:LABEL]",
500
+ help="Dashed line(s) y = A + B*x (intercept, then slope, as in "
501
+ "R's abline), across the whole panel, labelled if :LABEL is "
502
+ "given. Bare --abline is the identity line y = x (0:1). A "
503
+ "negative intercept needs =: --abline=-1:2. Repeatable.",
504
+ )
426
505
  if vertical:
427
506
  g.add_argument(
428
507
  "--vline",
@@ -57,7 +57,8 @@ using a command for the first time.
57
57
  `cleannames`, which also fixes headers such as `Sample ID` or `GC %`:
58
58
  `dftk cleannames data.tsv --backend duckdb -o data.parquet`. Parquet keeps
59
59
  the types, so later steps need no option.
60
- For a column that is already float, `--cast COL:Int64` turns it back.
60
+ For a column that is already float, `--cast COL:Int64` turns it back;
61
+ `--cast COL:str` makes numbers text (e.g. cluster numbers as categories).
61
62
  `--digits N` writes such columns in exponent form (`2.49e+08`) and warns.
62
63
 
63
64
  ## Output modes (`-o`, on every data command)
@@ -88,6 +89,14 @@ right; give the file before them) / `--sort COL:a COL:d`,
88
89
  `--dropna`, `--na_rep VAL`, `--removeheader`, and
89
90
  `--meta KEY=VALUE` (provenance, see below).
90
91
 
92
+ Missing values in one column: `--dropna` drops rows with a gap in any column;
93
+ for one column filter instead, `--prequery 'a.notna()'` (before the command
94
+ runs) or `--postquery 'a.notna()'` (on the output). "2 or missing" is
95
+ `'b == 2 or b.isna()'`, or in SQL `b = 2 OR b IS NULL`: a comparison with a
96
+ missing value is false. Inequality differs: in a pandas expression `b != 3`
97
+ keeps the missing rows, in SQL `b <> 3` drops them. With `--backend duckdb`
98
+ only empty cells are missing; a column holding the text `NA` is read as text.
99
+
91
100
  Output format: TSV unless `-o FILE` ends in `.json` (array of records),
92
101
  `.jsonl`, `.md` (Markdown table) or `.tex` (bare booktabs tabular, for
93
102
  `\input` in a LaTeX table); `--format tsv|json|jsonl|md|tex` does the same
@@ -175,7 +184,9 @@ Bonferroni per panel),
175
184
  `--textcol Pval n` numbers on the right, `-g` series per row, `--section` headers;
176
185
  `fit -o | forest -y marker -x effect --ci cilo,cihi` plots coefficients). `-g COL`
177
186
  overlays groups, `--subgraphcol COL` makes panels. `scat`, `line`, `hist` take
178
- `--vline X[:LABEL]` / `--hline Y[:LABEL]` reference lines (`forest` takes `--vline`, `box` `--hline`).
187
+ `--vline X[:LABEL]` / `--hline Y[:LABEL]` reference lines (`forest` takes `--vline`, `box` `--hline`);
188
+ `scat`, `line` take `--abline A:B[:LABEL]` for y = A + B*x (bare: y = x; `--abline=-1:2` for a
189
+ negative intercept).
179
190
 
180
191
  Other: `dataset NAME` loads a bundled example table, `annotate FILE.parquet`
181
192
  reads and writes provenance metadata, `clean` removes leftover temp pipe