Skip to content
Open
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
3 changes: 2 additions & 1 deletion src/spatialdata/models/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1045,13 +1045,14 @@ def _validate_table_annotation_metadata(cls, data: AnnData) -> None:
np.int64,
np.uint64,
"O",
"category",
]
and not pd.api.types.is_string_dtype(data.obs[attr[cls.INSTANCE_KEY]])
or (dtype == "O" and (val_dtype := type(data.obs[attr[cls.INSTANCE_KEY]].iloc[0])) is not str)
):
dtype = dtype if dtype != "O" else val_dtype
raise TypeError(
f"Only int, np.int16, np.int32, np.int64, uint equivalents or string allowed as dtype for "
f"Only int, np.int16, np.int32, np.int64, uint equivalents, categorical or string allowed as dtype for "
f"instance_key column in obs. Dtype found to be {dtype}"
)
expected_regions = attr[cls.REGION_KEY] if isinstance(attr[cls.REGION_KEY], list) else [attr[cls.REGION_KEY]]
Expand Down
8 changes: 8 additions & 0 deletions tests/models/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,14 @@ def test_table_model(
adata = AnnData(RNG.normal(size=(10, 2)), obs=obs)
table = model.parse(adata, region=region, region_key=region_key, instance_key="A")
assert region_key in table.obs

# categorical instance_key should be accepted
obs_cat = obs.copy()
obs_cat["A"] = pd.Categorical(obs_cat["A"])
adata_cat = AnnData(RNG.normal(size=(10, 2)), obs=obs_cat)
table_cat = model.parse(adata_cat, region=region, region_key=region_key, instance_key="A")
assert isinstance(table_cat.obs["A"].dtype, pd.CategoricalDtype)

assert isinstance(table.obs[region_key].dtype, pd.CategoricalDtype)
assert table.obs[region_key].cat.categories.tolist() == np.unique(region).tolist()
assert table.uns[TableModel.ATTRS_KEY][TableModel.REGION_KEY_KEY] == region_key
Expand Down
Loading