Subset on adata.uns["X"].var - help please!

Hi, I am using an AnnData object with lots of layers. In one of the uns. layers, it has another AnnData called “drug2cell”. This drug2cell then has a .var that contains a list of drugs. I would like to subset the list of drugs in this section, but keep it as an AnnData object. Essentially, I am trying to filter my AnnData object.

I would like to filter the dataframe adata.uns[‘drug2cell’].var column called [“drugs_present”] based on the df

I am trying to only keep .var rows that exist within a specific data frame. However, I need to keep it as an AnnData structure, not convert into a dataframe.

What I have tried already:

to_keep = df
adata_new = adata.uns[‘drug2cell’].var[adata.uns[‘drug2cell’].var[“drugs_present”].isin(to_keep)]

however it returns a dataframe, rather than an AnnData

Hi @spatts14,

Welcome to our forum :raised_hands:

Since adata.var is a dataframe, it makes sense that subsetting it returns a dataframe. You can subset the anndata object itself though:

drugs_to_keep = adata.uns["drug2cell"].var["drugs_present"].isin(to_keep)
adata_new_view = adata.uns["drug2cell"][:,drugs_to_keep]
# ^ this is a view, you can .copy() it to the new object

For views vs copies it might be helpful to check out e.g. this section of the documentation.