Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(fix): subsetting with empty list #1243

Merged
merged 11 commits into from
Dec 3, 2023
11 changes: 10 additions & 1 deletion anndata/_core/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,16 @@ def name_idx(i):
indexer = indexer.toarray()
indexer = np.ravel(indexer)
if not isinstance(indexer, (np.ndarray, pd.Index)):
indexer = np.array(indexer)
dtype = "int"
if (
all(isinstance(x, str) for x in indexer) and len(indexer) > 0
): # if not all, but any, then dtype=int will cause an error
dtype = "object"
elif (
any(isinstance(x, str) for x in indexer) and len(indexer) > 0
): # if not all, but any, there must be more than one type.
raise ValueError("Mixed type list indexers not supported.")
indexer = np.array(indexer, dtype=dtype)
flying-sheep marked this conversation as resolved.
Show resolved Hide resolved
if issubclass(indexer.dtype.type, (np.integer, np.floating)):
return indexer # Might not work for range indexes
elif issubclass(indexer.dtype.type, np.bool_):
Expand Down
15 changes: 15 additions & 0 deletions anndata/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -693,3 +693,18 @@ def test_x_none():
new = view.copy()
assert new.shape == (2, 0)
assert new.obs_names.tolist() == ["2", "3"]


def test_empty_list_subset():
orig = gen_adata((10, 10))
subset = orig[:, []]
assert subset.X.shape == (10, 0)
assert subset.obsm["sparse"].shape == (10, 100)
assert subset.varm["sparse"].shape == (0, 100)


def test_mixed_subset():
orig = gen_adata((10, 10))
with pytest.raises(ValueError) as exc:
orig[:, [1, "cell_c"]].X
assert exc.value.args[0] == "Mixed type list indexers not supported."