Skip to content

Commit d31f6df

Browse files
committed
Handle mixed-type and missing groupby values in joined categories
np.unique raises TypeError on object columns mixing ints and strings or containing missing values. Fall back to pd.unique in appearance order with missing values dropped, and cover the case with a mixed-type/missing-value regression test. Addresses review on #4385.
1 parent 682a0c3 commit d31f6df

2 files changed

Lines changed: 33 additions & 1 deletion

File tree

‎src/scanpy/plotting/legacy/_anndata.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1970,6 +1970,17 @@ def correlation_matrix( # noqa: PLR0912, PLR0913, PLR0915
19701970
return axs
19711971

19721972

1973+
def _unique_group_values(s: pd.Series) -> np.ndarray | pd.api.extensions.ExtensionArray:
1974+
try:
1975+
return np.unique(s)
1976+
except TypeError:
1977+
# object columns mixing types (e.g. ints and strings, or strings
1978+
# and missing values) cannot be sorted; keep appearance order and
1979+
# drop missing values, which never form categories
1980+
values = pd.unique(s)
1981+
return values[~pd.isna(values)]
1982+
1983+
19731984
def _prepare_dataframe( # noqa: PLR0912
19741985
adata: AnnData,
19751986
var_names: _VarNames | Mapping[str, _VarNames],
@@ -2085,7 +2096,7 @@ def _prepare_dataframe( # noqa: PLR0912
20852096
*(
20862097
obs_tidy[g].cat.categories
20872098
if isinstance(obs_tidy[g].dtype, CategoricalDtype)
2088-
else np.unique(obs_tidy[g])
2099+
else _unique_group_values(obs_tidy[g])
20892100
for g in groupby
20902101
)
20912102
)

‎tests/plotting/legacy/test_plotting.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,27 @@ def test_multi_groupby_partial_nan(plot_fn):
446446
assert not any("nan" in str(c) for c in plot.categories)
447447

448448

449+
@pytest.mark.parametrize(
450+
"plot_fn",
451+
[sc.pl.dotplot, sc.pl.matrixplot],
452+
ids=["dotplot", "matrixplot"],
453+
)
454+
def test_multi_groupby_mixed_type(plot_fn):
455+
"""Multi-column `groupby` accepts object columns mixing types and
456+
missing values."""
457+
adata = pbmc68k_reduced()
458+
mixed = np.empty(len(adata), dtype=object)
459+
mixed[::2] = "control"
460+
mixed[1::2] = 1
461+
mixed[:10] = np.nan
462+
adata.obs["mixed"] = mixed
463+
plot = plot_fn(adata, adata.var_names[:4], ["bulk_labels", "mixed"], return_fig=True)
464+
categories = [str(c) for c in plot.categories]
465+
assert not any("nan" in c for c in categories)
466+
assert any(c.endswith("_control") for c in categories)
467+
assert any(c.endswith("_1") for c in categories)
468+
469+
449470
def test_dotplot_add_totals(plot_cmp):
450471
pbmc = pbmc68k_reduced()
451472
markers = {"T-cell": "CD3D", "B-cell": "CD79A", "myeloid": "CST3"}

0 commit comments

Comments
 (0)