From 3fbf837d68de3857dae99bdd57c1b5a549c43f38 Mon Sep 17 00:00:00 2001 From: Philipp Weiler Date: Wed, 6 Mar 2024 15:12:52 +0100 Subject: [PATCH] Update `to_df` Add argument `obs` to include columns from `.obs` in generated metadata. --- anndata/_core/anndata.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/anndata/_core/anndata.py b/anndata/_core/anndata.py index 9ba69c724..a00f6951b 100644 --- a/anndata/_core/anndata.py +++ b/anndata/_core/anndata.py @@ -1284,7 +1284,7 @@ def transpose(self) -> AnnData: T = property(transpose) - def to_df(self, layer=None) -> pd.DataFrame: + def to_df(self, layer=None, obs: Optional[Union[str, List[str]]]=None) -> pd.DataFrame: """\ Generate shallow :class:`~pandas.DataFrame`. @@ -1299,6 +1299,8 @@ def to_df(self, layer=None) -> pd.DataFrame: ------ layer : str Key for `.layers`. + obs + Column(s) of `.obs` to include in DataFrame. """ if layer is not None: X = self.layers[layer] @@ -1308,7 +1310,11 @@ def to_df(self, layer=None) -> pd.DataFrame: X = self.X if issparse(X): X = X.toarray() - return pd.DataFrame(X, index=self.obs_names, columns=self.var_names) + + df = pd.DataFrame(X, index=self.obs_names, columns=self.var_names) + if obs is not None: + df = df.merge(self.obs[obs], left_index=True, right_index=True) + return df def _get_X(self, use_raw=False, layer=None): """\