Remove samples/rows from anndata

I can see how to remove columns from anndata ie

keep = ['a','b','c']

adata = adata [:, keep]

How does one remove rows/sets of samples from anndata.obs and anndata.x?

for example remove adata.obs[Region='reg012']

adata.obs

enter image description here

Everything is connected, so you can’t remove rows from .obs without removing rows from the whole object. In your case you want to do one of the following:

adata[adata.obs["Region"] != "reg012"]
adata[adata.obs.query("Region != 'reg012'").index]
adata[[r != "reg012" for r in adata.obs.Region]]
3 Likes

@adamgayoso thanks.
How does one do the inverse of keep for adata.var_names?
ie to exclude based on input list rather than include.
exclude = ['A','B','C']
àdata = adata[:, exclude]

adata = adata[:, ~adata.var_names.isin(exclude)]

Tilde is “not”, so this reads like “var names that are not in exclude”

1 Like

Hi there. If I have a list of cluster labels. And I want to remove all the cells in my anndata that have a label that belongs to said list called clusters_to_remove. How can I go about doing that? @adamgayoso

clusterstoremove= [‘1’,‘2’,‘3’]
adata = adata[adata.obs.clustercolumname.isin(clusterstoremove)==FALSE].copy()

1 Like