22
33from collections .abc import Iterator
44from dataclasses import dataclass
5- from typing import Literal
5+ from typing import Any , Callable , Literal , Optional
66
77from anndata import AnnData
88
@@ -21,12 +21,12 @@ class ToCategoryIterator(ToIterable):
2121 axis (int | str): The axis along which to iterate over the categories. Can be either 0, 1, "obs" or "var".
2222 0 or "obs" means the categories are in the observation axis.
2323 1 or "var" means the categories are in the variable axis.
24- preserve_categories (bool ): Preserves the categories in the resulting AnnData obs and var Series if `preserve_categories` is True.
24+ preserve_categories (list ): If not None, preserves the indicated categories from the Anndata ' obs' and ' var'
2525 """
2626
2727 category : str
2828 axis : Literal [0 , 1 , "obs" , "var" ] = "obs"
29- preserve_categories : bool = True
29+ preserve_categories : Optional [ list [ str ]] = []
3030
3131 def __post_init__ (self ):
3232 if self .axis not in (0 , 1 , "obs" , "var" ):
@@ -51,13 +51,15 @@ def __call__(self, adata: AnnData) -> Iterator[AnnData]:
5151 cats_df = get_from_loc (adata , f"{ self .axis } /{ self .category } " )
5252 cats = cats_df .dtypes .categories
5353 preserved_categories = {"obs" : {}, "var" : {}}
54- if self .preserve_categories :
55- for axis in ("obs" , "var" ):
56- adata_axis = getattr (adata , axis )
57- if adata_axis is not None :
58- for key in adata_axis .keys ():
59- if adata_axis [key ].dtype .name == "category" :
60- preserved_categories [axis ][key ] = adata_axis [key ].cat .categories
54+
55+ if self .preserve_categories is not None :
56+ for key in self .preserve_categories :
57+ for axis in ("obs" , "var" ):
58+ adata_axis = getattr (adata , axis )
59+ if adata_axis is not None :
60+ if key in adata_axis .keys ():
61+ if adata_axis [key ].dtype .name == "category" :
62+ preserved_categories [axis ][key ] = adata_axis [key ].cat .categories
6163
6264 for cat in cats :
6365 # TODO(syelman): is this wise? Maybe create copy only if preserve_categories is True?
0 commit comments