dataframe-toolkit 0.22.0__tar.gz → 0.22.1__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.22.0 → dataframe_toolkit-0.22.1}/PKG-INFO +2 -2
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/README.md +1 -1
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/pyproject.toml +1 -1
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/pyproject.toml.orig +1 -1
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/eval_cmd.py +10 -8
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/line_cmd.py +35 -5
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/manhattan_cmd.py +3 -3
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/scat_cmd.py +3 -3
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/stat_cmd.py +7 -2
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/common/evalfuncs.py +93 -27
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/__init__.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/cli.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/__init__.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/annotate_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/append_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/base.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/binx_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/chi_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/clean_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/cleannames_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/concat_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/corr_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/dataset_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/describe_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/explode_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/fit_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/func_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/heatmap_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/help.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/hist_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/implode_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/info_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/interp_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/locus_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/melt_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/merge_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/pairs_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/pivot_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/print_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/qq_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/query_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/randvar_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/sample_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/scale_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/segid_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/skill_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/split_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/test_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/transpose_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/commands/wstat_cmd.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/common/__init__.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/common/copula.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/common/docformats.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/common/gwas.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/common/io.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/common/plot.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/common/seed.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/common/seq.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/common/stats.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/io.py +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/skills/dftk/SKILL.md +0 -0
- {dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/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.22.
|
|
3
|
+
Version: 0.22.1
|
|
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
|
|
@@ -162,7 +162,7 @@ publication-quality output.
|
|
|
162
162
|
| Command | Description |
|
|
163
163
|
|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
164
164
|
| `scat` | Scatter plot; OLS/robust or LOWESS fit (`--fit lowess`, one per group with `-g`), hexagonal binning for large tables (`--hexbin`), bubble size (`--sizecol`), colour (`--colorcol`) |
|
|
165
|
-
| `line` | Line plot; optional error bars (`--yerr`) or
|
|
165
|
+
| `line` | Line plot; optional error bars (`--yerr`) or intervals (`--yci lo,hi`), `-ls none -m o` for points only, and fit overlay |
|
|
166
166
|
| `hist` | Histogram or KDE (`--kde`); normalisation, cumulative mode, mean±σ annotation (`--stats`) |
|
|
167
167
|
| `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
|
|
168
168
|
| `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
|
|
@@ -132,7 +132,7 @@ publication-quality output.
|
|
|
132
132
|
| Command | Description |
|
|
133
133
|
|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
|
134
134
|
| `scat` | Scatter plot; OLS/robust or LOWESS fit (`--fit lowess`, one per group with `-g`), hexagonal binning for large tables (`--hexbin`), bubble size (`--sizecol`), colour (`--colorcol`) |
|
|
135
|
-
| `line` | Line plot; optional error bars (`--yerr`) or
|
|
135
|
+
| `line` | Line plot; optional error bars (`--yerr`) or intervals (`--yci lo,hi`), `-ls none -m o` for points only, and fit overlay |
|
|
136
136
|
| `hist` | Histogram or KDE (`--kde`); normalisation, cumulative mode, mean±σ annotation (`--stats`) |
|
|
137
137
|
| `chi` | Corner-resolved chi-plot: whether tail dependence sits in the lower or upper corner |
|
|
138
138
|
| `heatmap` | Coloured grid of values from a long (`-x -y -v`) or wide (`-y`) table; correlograms from `corr --all`, `--annot`, `--lower` |
|
|
@@ -109,14 +109,16 @@ Available special functions:
|
|
|
109
109
|
sum mean std min max median
|
|
110
110
|
|
|
111
111
|
Conditional assignment:
|
|
112
|
-
where(
|
|
113
|
-
— np.where-style
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
112
|
+
where(condition, value if true, value if false)
|
|
113
|
+
— np.where-style. Each argument is a column, a quoted string
|
|
114
|
+
("foo"), a number, or a pandas expression of the columns
|
|
115
|
+
(-tip, tip * 2). The condition must be true or false (or 0
|
|
116
|
+
and 1), e.g. a true/false column or tip > 3; missing counts as
|
|
117
|
+
false. An unquoted word that is not a column is an error.
|
|
118
|
+
Examples:
|
|
119
|
+
dftk dataset tips -o \\
|
|
120
|
+
| dftk eval -f 'label = where(total_bill > 30, "large", "small")'
|
|
121
|
+
dftk dataset tips -o | dftk eval -f "signed = where(sex == 'Male', -tip, tip)"
|
|
120
122
|
|
|
121
123
|
Bitwise:
|
|
122
124
|
applymask(col, mask_col) — col & mask_col
|
|
@@ -42,13 +42,26 @@ from dftk.common.plot import (
|
|
|
42
42
|
# ---------------------------------------------------------------------------
|
|
43
43
|
|
|
44
44
|
|
|
45
|
+
def yci_columns(args) -> list[str]:
|
|
46
|
+
"""The two column names of --yci LO,HI ([] without it)."""
|
|
47
|
+
if not args.yci:
|
|
48
|
+
return []
|
|
49
|
+
cols = [c.strip() for c in args.yci.split(",")]
|
|
50
|
+
if len(cols) != 2 or not all(cols):
|
|
51
|
+
raise ValueError(
|
|
52
|
+
f"--yci takes two column names separated by a comma, e.g. "
|
|
53
|
+
f"--yci cilo,cihi; not {args.yci!r}."
|
|
54
|
+
)
|
|
55
|
+
return cols
|
|
56
|
+
|
|
57
|
+
|
|
45
58
|
def _resolve_yerr(df, args):
|
|
46
59
|
"""Return yerr array for df, or None. Handles --yerr and --yci."""
|
|
47
60
|
if args.yerr is not None:
|
|
48
61
|
err = df[args.yerr].values
|
|
49
62
|
return [err, err]
|
|
50
63
|
if args.yci is not None:
|
|
51
|
-
lo_col, hi_col = args
|
|
64
|
+
lo_col, hi_col = yci_columns(args)
|
|
52
65
|
lo = (df[args.ycol] - df[lo_col]).values
|
|
53
66
|
hi = (df[hi_col] - df[args.ycol]).values
|
|
54
67
|
return [lo, hi]
|
|
@@ -109,6 +122,7 @@ def _line_ax(ax, df, args, title_suffix: str = ""):
|
|
|
109
122
|
legendloc = tuple(args.legendloc) if args.legendloc else "best"
|
|
110
123
|
marker = getattr(args, "marker", "")
|
|
111
124
|
drawstyle = getattr(args, "drawstyle", "default")
|
|
125
|
+
linestyle = getattr(args, "linestyle", "-")
|
|
112
126
|
|
|
113
127
|
if args.groupcol is not None:
|
|
114
128
|
for groupname, gdf in subgraph_groups(
|
|
@@ -124,6 +138,7 @@ def _line_ax(ax, df, args, title_suffix: str = ""):
|
|
|
124
138
|
yerr=yerr,
|
|
125
139
|
marker=marker,
|
|
126
140
|
drawstyle=drawstyle,
|
|
141
|
+
linestyle=linestyle,
|
|
127
142
|
label=label,
|
|
128
143
|
capsize=3,
|
|
129
144
|
)
|
|
@@ -137,6 +152,7 @@ def _line_ax(ax, df, args, title_suffix: str = ""):
|
|
|
137
152
|
yerr=yerr,
|
|
138
153
|
marker=marker,
|
|
139
154
|
drawstyle=drawstyle,
|
|
155
|
+
linestyle=linestyle,
|
|
140
156
|
label=label if label else None,
|
|
141
157
|
capsize=3,
|
|
142
158
|
)
|
|
@@ -179,11 +195,17 @@ Symmetric error bars (mean ± SEM flipper length per species):
|
|
|
179
195
|
dftk dataset penguins -o | dftk stat -c flipper_length_mm -g species -o \\
|
|
180
196
|
| dftk line -x species -y mean --yerr sem
|
|
181
197
|
|
|
182
|
-
Asymmetric
|
|
198
|
+
Asymmetric intervals: mean bill length per species, with a bar over the
|
|
199
|
+
middle 95 % of the values (stat's cilo and cihi are percentiles of the data):
|
|
183
200
|
|
|
184
201
|
dftk dataset penguins -o | dftk stat -c bill_length_mm -g species -o \\
|
|
185
202
|
| dftk line -x species -y mean --yci cilo,cihi
|
|
186
203
|
|
|
204
|
+
Points with intervals and no connecting line (a dot-and-whisker plot):
|
|
205
|
+
|
|
206
|
+
dftk dataset penguins -o | dftk stat -c bill_length_mm -g species -o \\
|
|
207
|
+
| dftk line -x species -y mean --yci cilo,cihi -ls none -m o
|
|
208
|
+
|
|
187
209
|
Subplot grid, one panel per month (year-over-year trend within each month):
|
|
188
210
|
|
|
189
211
|
dftk dataset flights -o | dftk line -x year -y passengers \\
|
|
@@ -232,6 +254,14 @@ class LineCommand(BaseCommand):
|
|
|
232
254
|
metavar="MARKER",
|
|
233
255
|
help="Matplotlib marker style (default: none).",
|
|
234
256
|
)
|
|
257
|
+
s.add_argument(
|
|
258
|
+
"-ls",
|
|
259
|
+
"--linestyle",
|
|
260
|
+
default="-",
|
|
261
|
+
metavar="STYLE",
|
|
262
|
+
help="Matplotlib line style: - -- : -. or none for points only, "
|
|
263
|
+
"e.g. estimates with --yci intervals (default: -).",
|
|
264
|
+
)
|
|
235
265
|
s.add_argument(
|
|
236
266
|
"--drawstyle",
|
|
237
267
|
default="default",
|
|
@@ -288,15 +318,15 @@ class LineCommand(BaseCommand):
|
|
|
288
318
|
if not args.xcol or not args.ycol:
|
|
289
319
|
raise ValueError("--xcol (-x) and --ycol (-y) are required.")
|
|
290
320
|
|
|
291
|
-
|
|
321
|
+
# --yci names two columns in one string: add them by name
|
|
322
|
+
df = io.read(args, columns=option_columns(args, *yci_columns(args)))
|
|
292
323
|
check_cols(df, [args.xcol, args.ycol], "-x/-y")
|
|
293
324
|
check_cols(df, args.groupcol, "-g/--groupcol")
|
|
294
325
|
check_cols(df, args.subgraphcol, "--subgraphcol")
|
|
295
326
|
if args.yerr:
|
|
296
327
|
check_cols(df, [args.yerr], "--yerr")
|
|
297
328
|
if args.yci:
|
|
298
|
-
|
|
299
|
-
check_cols(df, [lo.strip(), hi.strip()], "--yci")
|
|
329
|
+
check_cols(df, yci_columns(args), "--yci")
|
|
300
330
|
|
|
301
331
|
if args.file:
|
|
302
332
|
import matplotlib
|
|
@@ -92,9 +92,9 @@ them; points past --sig in red.
|
|
|
92
92
|
Here the second scan is the example scan with every chi-squared halved,
|
|
93
93
|
and melt stacks the two columns into one, with a study column:
|
|
94
94
|
|
|
95
|
-
dftk dataset gwas -o
|
|
96
|
-
| dftk eval -f "half = Chisq / 2" --select Chr pos Chisq half -o
|
|
97
|
-
| dftk melt -i Chr pos -d study -v chi2 -o
|
|
95
|
+
dftk dataset gwas -o \\
|
|
96
|
+
| dftk eval -f "half = Chisq / 2" --select Chr pos Chisq half -o \\
|
|
97
|
+
| dftk melt -i Chr pos -d study -v chi2 -o \\
|
|
98
98
|
| dftk manhattan --chi2col chi2 --miami study --sigcolor red -f miami.png
|
|
99
99
|
|
|
100
100
|
With more than two scans in the column, name the two: --miami study a b.
|
|
@@ -274,17 +274,17 @@ can overshoot the data; a larger --frac or --xlim helps:
|
|
|
274
274
|
Hexagonal binning for large tables (54,000 diamonds), log colour scale and
|
|
275
275
|
log axes; hexagons are binned on the log scale:
|
|
276
276
|
|
|
277
|
-
dftk dataset diamonds -o | dftk scat -x carat -y price
|
|
277
|
+
dftk dataset diamonds -o | dftk scat -x carat -y price \\
|
|
278
278
|
--hexbin --hexlog --logx --logy
|
|
279
279
|
|
|
280
280
|
Colour each hexagon by the mean of another column instead of the count:
|
|
281
281
|
|
|
282
|
-
dftk dataset diamonds -o | dftk scat -x carat -y price
|
|
282
|
+
dftk dataset diamonds -o | dftk scat -x carat -y price \\
|
|
283
283
|
--hexbin --colorcol depth --gridsize 50
|
|
284
284
|
|
|
285
285
|
One hexbin panel per group, all on the same colour scale:
|
|
286
286
|
|
|
287
|
-
dftk dataset diamonds -o | dftk scat -x carat -y price
|
|
287
|
+
dftk dataset diamonds -o | dftk scat -x carat -y price \\
|
|
288
288
|
--hexbin --hexlog --subgraphcol cut --gridsize 40
|
|
289
289
|
|
|
290
290
|
Publication figure (Nature single column, PDF):
|
|
@@ -86,7 +86,10 @@ def _ci(name: str, level: float, method: str):
|
|
|
86
86
|
"""
|
|
87
87
|
|
|
88
88
|
def cifunction(a):
|
|
89
|
-
|
|
89
|
+
# missing values left out, as for the other statistics
|
|
90
|
+
a = np.asarray(a, dtype=float)
|
|
91
|
+
a = a[~np.isnan(a)]
|
|
92
|
+
return np.percentile(a, q=level, method=method) if a.size else np.nan
|
|
90
93
|
|
|
91
94
|
cifunction.__name__ = name
|
|
92
95
|
return cifunction
|
|
@@ -206,7 +209,9 @@ class StatCommand(BaseCommand):
|
|
|
206
209
|
)
|
|
207
210
|
g.add_argument(
|
|
208
211
|
"--confidencelevel",
|
|
209
|
-
help="
|
|
212
|
+
help="Percent of the values between cilo and cihi, which are "
|
|
213
|
+
"percentiles of the data (default: 95.0, the 2.5th and 97.5th); "
|
|
214
|
+
"for a confidence interval of a statistic, see --bootstrap",
|
|
210
215
|
type=float,
|
|
211
216
|
default=95.0,
|
|
212
217
|
metavar="PCT",
|
|
@@ -183,20 +183,39 @@ class _StatsFunc:
|
|
|
183
183
|
return table.apply(lambda row: self.row_func(row.to_numpy()), axis=1)
|
|
184
184
|
|
|
185
185
|
|
|
186
|
-
def
|
|
187
|
-
"""
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
186
|
+
def split_arguments(body: str) -> list[str]:
|
|
187
|
+
"""Split a call's argument string at the commas outside quotes and
|
|
188
|
+
brackets: 'a > 0, "x, y", f(b, c)' gives three arguments."""
|
|
189
|
+
parts, depth, quote, start = [], 0, None, 0
|
|
190
|
+
for i, ch in enumerate(body):
|
|
191
|
+
if quote:
|
|
192
|
+
if ch == quote:
|
|
193
|
+
quote = None
|
|
194
|
+
elif ch in "\"'":
|
|
195
|
+
quote = ch
|
|
196
|
+
elif ch in "([{":
|
|
197
|
+
depth += 1
|
|
198
|
+
elif ch in ")]}":
|
|
199
|
+
depth -= 1
|
|
200
|
+
elif ch == "," and depth == 0:
|
|
201
|
+
parts.append(body[start:i].strip())
|
|
202
|
+
start = i + 1
|
|
203
|
+
parts.append(body[start:].strip())
|
|
204
|
+
return parts
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
_IDENTIFIER = re.compile(r"[A-Za-z_]\w*")
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _resolve_where_val(val: str, df: pd.DataFrame, role: str):
|
|
211
|
+
"""Resolve a where() argument to a scalar or a Series.
|
|
212
|
+
|
|
213
|
+
In order: a quoted string ("foo" or 'foo') is that text; a column name
|
|
214
|
+
is the column; a number is the number; anything else is a pandas
|
|
215
|
+
expression of the columns (-tip, tip * 2, tip > 3).
|
|
195
216
|
"""
|
|
196
217
|
s = val.strip()
|
|
197
|
-
if (s
|
|
198
|
-
s.startswith("'") and s.endswith("'")
|
|
199
|
-
):
|
|
218
|
+
if len(s) >= 2 and s[0] == s[-1] and s[0] in "\"'":
|
|
200
219
|
return s[1:-1]
|
|
201
220
|
if s in df.columns:
|
|
202
221
|
return df[s]
|
|
@@ -208,26 +227,72 @@ def _resolve_where_val(val: str, df: pd.DataFrame):
|
|
|
208
227
|
return float(s)
|
|
209
228
|
except ValueError:
|
|
210
229
|
pass
|
|
211
|
-
|
|
230
|
+
if s in ("True", "False"):
|
|
231
|
+
return s == "True"
|
|
232
|
+
if _IDENTIFIER.fullmatch(s):
|
|
233
|
+
hint = (
|
|
234
|
+
f" Available columns: {list(df.columns)}"
|
|
235
|
+
if role == "condition"
|
|
236
|
+
else f' For text, quote it: "{s}".'
|
|
237
|
+
)
|
|
238
|
+
raise FormulaMistake(f"where(): the {role} {s!r} is not a column.{hint}")
|
|
239
|
+
try:
|
|
240
|
+
return df.eval(s)
|
|
241
|
+
except Exception as exc:
|
|
242
|
+
raise FormulaMistake(
|
|
243
|
+
f"where(): can't evaluate the {role} {s!r}: {exc}"
|
|
244
|
+
) from None
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _where_condition(val: str, df: pd.DataFrame) -> np.ndarray:
|
|
248
|
+
"""The condition as a boolean array: a true/false column or expression,
|
|
249
|
+
or numbers 0 and 1. Missing counts as false."""
|
|
250
|
+
cond = _resolve_where_val(val, df, "condition")
|
|
251
|
+
if not isinstance(cond, pd.Series):
|
|
252
|
+
raise FormulaMistake(
|
|
253
|
+
f"where(): the condition {val!r} must be a column or an expression "
|
|
254
|
+
"of columns that is true or false, e.g. where(tip > 3, ...)."
|
|
255
|
+
)
|
|
256
|
+
if pd.api.types.is_bool_dtype(cond):
|
|
257
|
+
return cond.fillna(False).to_numpy(dtype=bool)
|
|
258
|
+
if pd.api.types.is_numeric_dtype(cond) and cond.dropna().isin([0, 1]).all():
|
|
259
|
+
return (cond == 1).to_numpy()
|
|
260
|
+
if cond.dropna().map(lambda v: isinstance(v, (bool, np.bool_))).all():
|
|
261
|
+
return cond.fillna(False).astype(bool).to_numpy()
|
|
262
|
+
shown = [v.item() if hasattr(v, "item") else v for v in pd.unique(cond.dropna())]
|
|
263
|
+
shown = shown[:3]
|
|
264
|
+
raise FormulaMistake(
|
|
265
|
+
f"where(): the condition {val!r} must be true or false (or 0 and 1), "
|
|
266
|
+
f"but it holds values like {shown}. Compare it, e.g. "
|
|
267
|
+
f"where({val} == {shown[0]!r}, ...)."
|
|
268
|
+
if shown
|
|
269
|
+
else f"where(): the condition {val!r} must be true or false."
|
|
270
|
+
)
|
|
212
271
|
|
|
213
272
|
|
|
214
273
|
class _WhereFunc:
|
|
215
|
-
"""Callable for ``where(
|
|
274
|
+
"""Callable for ``where(cond, true_val, false_val)`` using ``np.where``.
|
|
216
275
|
|
|
217
|
-
Receives the full DataFrame so that
|
|
218
|
-
|
|
276
|
+
Receives the full DataFrame so that each argument can be a column, a
|
|
277
|
+
quoted string, a number or a pandas expression (_resolve_where_val).
|
|
219
278
|
"""
|
|
220
279
|
|
|
221
|
-
def __init__(self,
|
|
222
|
-
self.
|
|
280
|
+
def __init__(self, cond: str, true_val: str, false_val: str) -> None:
|
|
281
|
+
self.cond = cond
|
|
223
282
|
self.true_val = true_val
|
|
224
283
|
self.false_val = false_val
|
|
225
284
|
|
|
226
285
|
def __call__(self, df: pd.DataFrame):
|
|
227
|
-
cond =
|
|
228
|
-
true_res = _resolve_where_val(self.true_val, df)
|
|
229
|
-
false_res = _resolve_where_val(self.false_val, df)
|
|
230
|
-
|
|
286
|
+
cond = _where_condition(self.cond, df)
|
|
287
|
+
true_res = _resolve_where_val(self.true_val, df, "value if true")
|
|
288
|
+
false_res = _resolve_where_val(self.false_val, df, "value if false")
|
|
289
|
+
try:
|
|
290
|
+
return np.where(cond, true_res, false_res)
|
|
291
|
+
except TypeError: # text and numbers: numpy has no common type
|
|
292
|
+
return np.where(
|
|
293
|
+
cond, np.asarray(true_res, dtype=object),
|
|
294
|
+
np.asarray(false_res, dtype=object),
|
|
295
|
+
) # fmt: skip
|
|
231
296
|
|
|
232
297
|
|
|
233
298
|
SPECIAL_FUNCTIONS = (
|
|
@@ -292,12 +357,13 @@ def special_function(formula: str, df_columns: list[str]):
|
|
|
292
357
|
)
|
|
293
358
|
|
|
294
359
|
if func_name == "where":
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
"where(
|
|
360
|
+
args = split_arguments(body)
|
|
361
|
+
if len(args) != 3 or not all(args):
|
|
362
|
+
raise FormulaMistake(
|
|
363
|
+
f"where() takes 3 arguments, where(condition, value if true, "
|
|
364
|
+
f"value if false), not {len(args)}: {formula!r}"
|
|
299
365
|
)
|
|
300
|
-
return dest, _WhereFunc(
|
|
366
|
+
return dest, _WhereFunc(*args), []
|
|
301
367
|
|
|
302
368
|
if func_name == "overlap":
|
|
303
369
|
func = partial(lambda x: max(0, min(x[1], x[3]) - max(x[0] - 1, x[2] - 1)))
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{dataframe_toolkit-0.22.0 → dataframe_toolkit-0.22.1}/src/dftk/skills/dftk/references/snakemake.md
RENAMED
|
File without changes
|