Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,23 @@ 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

- 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).
- GitHub releases stopped at 0.11.1: they were cut by hand, and the release
checklist never said so. PyPI, quay and the benchmark page were unaffected.
`publish.yml` now creates the release from the changelog section (#114).
Expand Down
19 changes: 11 additions & 8 deletions docs/reference/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |

Expand Down Expand Up @@ -583,13 +583,16 @@ 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
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.
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 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
Expand Down
6 changes: 4 additions & 2 deletions src/adata/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 make categoricals of their text, "
"even numeric-looking ones (leiden's 0, 1, 10)",
),
auto_categorical: bool = typer.Option(
True,
Expand All @@ -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
Expand Down
20 changes: 11 additions & 9 deletions src/adata/formats/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down
79 changes: 71 additions & 8 deletions tests/test_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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", "<na>", "3", "4", "5", "6"]

plain, out = _import("dataframe", written, "obs", csv, "-i", "cell", "--no-auto-categorical")
assert plain.exit_code == 0, _out(plain)
Expand All @@ -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", "<na>", "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
Expand Down
Loading