From 00de393875d07f8e8d42e23d23dc0ff9ac1475b9 Mon Sep 17 00:00:00 2001 From: Aljes Date: Thu, 26 Nov 2026 16:14:03 +0000 Subject: [PATCH 1/2] --categorical reads numeric-looking labels as text (#124) A column named in --categorical whose values looked like numbers (leiden's "0", "1", "10") was kept as int64 with only a note, so an export, edit and import of obs lost the clusters' labels, and "007" its zeros. A forced column is now always read as text and stored as a categorical: numbers and True/False keep the text they were written as, and what pandas reads as missing stays a gap, matching pd.read_csv(dtype=str) and anndata's strings_to_categoricals. Past the cap of distinct values it is written as strings, numbers included, as the warning already said. --keep-dtypes and a columns-only import, also raised in #124, are noted in STATUS.md as follow-ups. Co-Authored-By: Claude Opus 5.5 --- STATUS.md | 7 +++ docs/reference/commands.md | 11 +++-- src/adata/cli.py | 6 ++- src/adata/formats/dataframe.py | 20 +++++---- tests/test_import.py | 79 ++++++++++++++++++++++++++++++---- 5 files changed, 100 insertions(+), 23 deletions(-) diff --git a/STATUS.md b/STATUS.md index 127a475..b4141af 100644 --- a/STATUS.md +++ b/STATUS.md @@ -33,6 +33,13 @@ theirs. ## Follow-ups noticed +- From #124 (`--categorical` now reads numeric-looking labels as text): + - `import dataframe --keep-dtypes`, to keep the encodings the existing + frame has for columns of the same name (category order, `ordered`, + numeric dtypes), so a pipeline need not list every categorical. + - An import that adds or replaces only the CSV's columns, joined on the + index, and leaves the frame's other columns as they are ("attach + metadata" without a round trip of the whole frame). - From waves 3 and 4 of the audit fixes: - The streaming transpose and other users of `csr_build.BucketSorter` append every input block to every bucket, (nnz/chunk)² appends, and diff --git a/docs/reference/commands.md b/docs/reference/commands.md index f5916b5..f213b78 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -544,7 +544,7 @@ adata import image data.h5ad uns/spatial/hires tissue.png --inplace | `--inplace` | all | Replace the source; the new store is written beside it first | | `--no-space-check` | all | Write even if the disk looks too small | | `--index-column`, `-i` | `dataframe` | Column that becomes the index; the first by default | -| `--categorical` | `dataframe` | Comma separated text columns to make categoricals | +| `--categorical` | `dataframe` | Comma separated columns to read as text and make categoricals | | `--auto-categorical / --no-auto-categorical` | `dataframe` | Make text columns that repeat a value categoricals (default on) | | `--chunk`, `-C` | `array` | Elements a block (below) | @@ -583,9 +583,12 @@ an integer column float64, with NaN), True/False as bool, and text otherwise. A number is what pandas reads as one, so a label such as `1_1` stays text, and whole numbers past int64 become uint64, or text past uint64. A text column that repeats a value becomes a categorical, as anndata makes -it. Use `--categorical col1,col2` to make specific text columns categoricals -whatever their values (numeric columns stay numeric), or -`--no-auto-categorical` to keep all text as `string-array`. A row with more +it. Use `--categorical col1,col2` to read specific columns as text and make +them categoricals whatever their values: leiden clusters `0`, `1`, `10` stay +labels rather than becoming int64, and `007` keeps its zeros. Missing values +(as pandas reads them) are gaps, and a column with more than 65,536 distinct +values is written as `string-array`. Use `--no-auto-categorical` to keep +all other text as `string-array`. A row with more or fewer fields than the header, a header that repeats a name, a column with no name (as pandas writes an unnamed index) or named `_index` besides the index, and a `--categorical` name the file does not have are refused before diff --git a/src/adata/cli.py b/src/adata/cli.py index 02454f7..3ba4e7e 100644 --- a/src/adata/cli.py +++ b/src/adata/cli.py @@ -1544,7 +1544,8 @@ def import_dataframe( categorical: Optional[str] = typer.Option( None, "--categorical", - help="Comma separated columns to force to categorical", + help="Comma separated columns to read as text and make categoricals, " + "numeric-looking labels such as leiden's 0, 1, 10 included", ), auto_categorical: bool = typer.Option( True, @@ -1557,7 +1558,8 @@ def import_dataframe( A text column that repeats a value becomes a categorical, as anndata makes it; pass --no-auto-categorical to keep text as plain strings, or - --categorical to force specific columns. + --categorical to make specific columns categoricals of their text, + whatever their values look like. Examples: adata import dataframe data.h5ad obs cells.csv -o out.h5ad -i cell_id diff --git a/src/adata/formats/dataframe.py b/src/adata/formats/dataframe.py index 5ebd93c..6ab2bb0 100644 --- a/src/adata/formats/dataframe.py +++ b/src/adata/formats/dataframe.py @@ -124,9 +124,10 @@ def import_dataframe( not by the file: the first types each column as `pd.read_csv` would (missing numbers are NaN, True/False is bool) and checks every row's width; the second writes the frame as anndata writes it, a text column - that repeats a value as a categorical. `categorical` names text columns - to make categoricals whatever their values, and `auto_categorical=False` - keeps every other text column as strings. + that repeats a value as a categorical. `categorical` names columns to + read as text and make categoricals whatever their values, numbers + included, and `auto_categorical=False` keeps every other text column as + strings. """ obj = check_target(obj, "dataframe") input_file = Path(input_file) @@ -158,16 +159,17 @@ def import_dataframe( for column in scan.columns: kind = scan.dtype_of(column) if column.name in forced: - if kind not in ("str", "category"): - console.print( - f"[yellow]Note:[/] {literal(repr(column.name))} holds {kind} values, so it " - "stays as it is rather than a categorical." - ) - elif column.seen is None: + # A forced column is read as text whatever its values look like: + # leiden's "0", "1", "10" are labels, and "007" keeps its zeros. + # The scan kept every column's distinct values as written, so + # numbers and True/False have their text to hand; what pandas + # reads as missing stays a gap, as `dtype=str` leaves it. + if column.seen is None: console.print( f"[yellow]Warning:[/] {literal(repr(column.name))} has more than " f"{CATEGORY_CAP:,} distinct values, so it is written as strings." ) + scan.overrides[column.name] = "str" else: scan.overrides[column.name] = "category" elif kind == "category" and not auto_categorical: diff --git a/tests/test_import.py b/tests/test_import.py index c03c8ec..e409753 100644 --- a/tests/test_import.py +++ b/tests/test_import.py @@ -621,10 +621,11 @@ def _import(kind, store, entry, source, *extra): return result, out -def _pandas_frame(csv: Path, index: str): +def _pandas_frame(csv: Path, index: str, text=()): """What anndata writes for `pd.read_csv`'s frame: text that repeats a - value becomes a categorical.""" - frame = pd.read_csv(csv).set_index(index) + value becomes a categorical. Columns in `text` are read as strings + (`dtype=str`), as `--categorical` reads them.""" + frame = pd.read_csv(csv, dtype={name: str for name in text}).set_index(index) frame.index.name = None frame.index = frame.index.astype(str) obj = ad.AnnData(obs=frame) @@ -738,16 +739,26 @@ def test_the_export_of_a_dataframe_imports_back_as_pandas_reads_it(temp_dir, bac def test_categorical_overrides_still_apply(written, temp_dir): - """--categorical makes a text column a categorical whatever its values, - and --no-auto-categorical keeps the others as strings.""" + """--categorical makes a column a categorical of its text whatever its + values, and --no-auto-categorical keeps the others as strings.""" csv = temp_dir / "cells.csv" csv.write_text(CELLS, encoding="utf-8") - forced, out = _import("dataframe", written, "obs", csv, "-i", "cell", "--categorical", "note,count") + forced, out = _import( + "dataframe", written, "obs", csv, "-i", "cell", "--categorical", "note,gappy,score,flag" + ) assert forced.exit_code == 0, _out(forced) - assert "'count' holds int64 values, so it stays as it is" in _out(forced) + assert "(6 categorical)" in _out(forced) # the four forced, label and flags got = _read(out).obs - assert got["note"].dtype == "category" and got["count"].dtype == "int64" + # Every value of `note` differs, so pandas' frame has no categorical to + # compare it with; the others repeat a value, as the oracle needs. + assert got["note"].dtype == "category" + assert _labels(got["note"]) == ["one", "two", "three", "four", "five", "six"] + expected = _pandas_frame(csv, "cell", text=["gappy", "score", "flag"]) + assert all(expected[c].dtype == "category" for c in ("gappy", "score", "flag")) + _same_frame(got.drop(columns="note"), expected.drop(columns="note")) + assert list(got["score"].cat.categories) == ["1.5", "2.5", "3.5", "4.5"] + assert _labels(got["gappy"]) == ["1", "", "3", "4", "5", "6"] plain, out = _import("dataframe", written, "obs", csv, "-i", "cell", "--no-auto-categorical") assert plain.exit_code == 0, _out(plain) @@ -760,6 +771,58 @@ def test_categorical_overrides_still_apply(written, temp_dir): assert "--categorical names 'nope', which cells.csv does not have" in _out(unknown) +def test_numeric_labels_named_categorical_survive_a_round_trip(temp_dir, backend): + """#124: a column named in --categorical whose values looked like + numbers (leiden's "0", "1", "10") stayed int64, with only a note, so an + export, edit and import lost the clusters' labels and "007" its zeros.""" + obs = pd.DataFrame( + { + "leiden": pd.Categorical(["0", "1", "0", "2", "1", "10"]), + "code": pd.Categorical(["007", "7", "007", None, "7", "0"]), + "celltype": pd.Categorical(["T", "B", "T", "NK", "B", "T"]), + "n_genes": [10, 20, 30, 40, 50, 60], + }, + index=[f"c{i}" for i in range(6)], + ) + path = backend_path(temp_dir, backend, "clusters") + obj = ad.AnnData(obs=obs) + obj.write_h5ad(path) if backend == "h5ad" else obj.write_zarr(path) + csv = temp_dir / "obs.csv" + exported = runner.invoke(app, ["export", "dataframe", str(path), "obs", "-o", str(csv)]) + assert exported.exit_code == 0, _out(exported) + + plain, _ = _import("dataframe", path, "obs", csv) + forced, out = _import("dataframe", path, "obs", csv, "--categorical", "leiden,code,celltype") + + assert plain.exit_code == 0, _out(plain) + assert forced.exit_code == 0, _out(forced) + got = _read(out).obs + _same_frame(got, _pandas_frame(csv, "_index", text=["leiden", "code"])) + assert list(got["leiden"].cat.categories) == ["0", "1", "2", "10"] + assert _labels(got["leiden"]) == list(obs["leiden"]) + assert _labels(got["code"]) == ["007", "7", "007", "", "7", "0"] + assert got["n_genes"].dtype == "int64" + + +def test_a_forced_numeric_column_past_the_cap_is_written_as_strings(written, temp_dir, monkeypatch): + """Past the cap of distinct values a forced column is written as text, + as the warning says, numbers included.""" + from adata.formats import table + + monkeypatch.setattr(table, "CATEGORY_CAP", 3) + csv = temp_dir / "cells.csv" + csv.write_text(CELLS, encoding="utf-8") + + result, out = _import("dataframe", written, "obs", csv, "-i", "cell", "--categorical", "count") + + assert result.exit_code == 0, _out(result) + # The message names the cap the module was imported with, not the patch. + assert re.search(r"'count' has more than [\d,]+ distinct values, so it is written as strings", _out(result)) + got = _read(out).obs + assert pd.api.types.is_string_dtype(got["count"]) and got["count"].dtype != "category" + assert _labels(got["count"]) == ["1", "2", "3", "4", "5", "6"] + + def test_a_dataframe_import_holds_a_block_not_the_file(temp_dir, monkeypatch): """F034: the whole CSV was read into a list of dicts and then a list per column, so memory grew with the file. Eight times the rows must not From 76e414ab1bf42ba4f7993e32b77c22deb9230a78 Mon Sep 17 00:00:00 2001 From: Aljes Date: Thu, 26 Nov 2026 16:42:45 +0000 Subject: [PATCH 2/2] Review: clearer --categorical help, reflowed docs, STATUS in progress Co-Authored-By: Claude Opus 5.5 --- STATUS.md | 9 ++++++--- docs/reference/commands.md | 10 +++++----- src/adata/cli.py | 4 ++-- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/STATUS.md b/STATUS.md index b4141af..a73b3dc 100644 --- a/STATUS.md +++ b/STATUS.md @@ -26,9 +26,12 @@ The conversion epic's sub-issues (#21–#30) are all done and ticked in #20. ## In progress -Nothing. The fixes from the October 2026 audit (epic #87, 164 findings in -16 batches) finished with 0.17.6; the sub-issues (#88–#103) are all done -and ticked in #87. The batch names in the follow-ups below (B1 to B10) are +- #124: `import dataframe --categorical` reads numeric-looking labels as + text (#125), for 0.17.7. + +The fixes from the October 2026 audit (epic #87, 164 findings in 16 +batches) finished with 0.17.6; the sub-issues (#88–#103) are all done and +ticked in #87. The batch names in the follow-ups below (B1 to B10) are theirs. ## Follow-ups noticed diff --git a/docs/reference/commands.md b/docs/reference/commands.md index f213b78..ce88b37 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -588,11 +588,11 @@ them categoricals whatever their values: leiden clusters `0`, `1`, `10` stay labels rather than becoming int64, and `007` keeps its zeros. Missing values (as pandas reads them) are gaps, and a column with more than 65,536 distinct values is written as `string-array`. Use `--no-auto-categorical` to keep -all other text as `string-array`. A row with more -or fewer fields than the header, a header that repeats a name, a column with -no name (as pandas writes an unnamed index) or named `_index` besides the -index, and a `--categorical` name the file does not have are refused before -the store is touched. +all other text as `string-array`. A row with more or fewer fields than the +header, a header that repeats a name, a column with no name (as pandas +writes an unnamed index) or named `_index` besides the index, and a +`--categorical` name the file does not have are refused before the store is +touched. For `dict`: an object becomes a mapping, and an array a typed array where its values share a type: strings, booleans, whole numbers (int64, or uint64 past diff --git a/src/adata/cli.py b/src/adata/cli.py index 3ba4e7e..d649909 100644 --- a/src/adata/cli.py +++ b/src/adata/cli.py @@ -1544,8 +1544,8 @@ def import_dataframe( categorical: Optional[str] = typer.Option( None, "--categorical", - help="Comma separated columns to read as text and make categoricals, " - "numeric-looking labels such as leiden's 0, 1, 10 included", + help="Comma separated columns to make categoricals of their text, " + "even numeric-looking ones (leiden's 0, 1, 10)", ), auto_categorical: bool = typer.Option( True,