Closed
Description
Hi,
I was wondering why subsetting of the anndata object does not work, but subsetting of the obs dataframe works when updating the obs dataframe. I got a little bit confused while trying to assign a custom cluster with values:
# get subset of cells that express GENE1
gene1_cells = list(adata[(adata.raw[:, ['GENE1']].X > 0),].obs.index)
# First solution: assign subset to cluster 1 -- does not work
adata[gene1_obs,:].obs["my_cluster"] = 1
# Second solution: assign subset to cluster 1 -- works!
adata.obs.loc[adata.obs.index.isin(gene1_cells), "my_cluster"] = 1
Would you know what the recommended way of doing this is and why is my first solution not working?
I appreciate any feedback as I'm into learning the ropes of scanpy now. PAGA got me :)
Thanks for your great work on scanpy btw!
Reacted by He, Peng 何鹏 and Eric Weitz
Metadata
Metadata
Assignees
Labels
No labels
Activity
falexwolf commentedon Apr 17, 2019
Hey! Thank you for using Scanpy!
If you print
adata[gene1_obs,:], you'll see that it generates a view onadata. If you try the annotations of the view, however, this view becomes a copy. This is a safety measure as most people treat subsets of the data matrix as if it was a copy. Views are necessary, however, to be able to index in a data matrix (also for efficiency reasons).But I realize that we should print warnings when someone tries to do this, similar to pandas, which also prints a warning if you do
df['col'].loc['a':'b'] = value.falexwolf commentedon Apr 17, 2019
We now print a warning. It might sometimes lead to some cluttered output, but it forces people to use

.copy()consistently and should prevent issues like the above.Commit is here: scverse/anndata@97ad1e4
tilofrei commentedon Apr 17, 2019
Thank you for the explanation and quick fix!