Skip to content

How to update obs-column only for subset of cells? #612

Closed

Description

@tilofrei

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!

Activity

  1. falexwolf commented on Apr 17, 2019

    @falexwolf
    Member

    Hey! Thank you for using Scanpy!

    # First solution: assign subset to cluster 1 -- does not work
    adata[gene1_obs,:].obs["my_cluster"] = 1
    

    If you print adata[gene1_obs,:], you'll see that it generates a view on adata. 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.

  2. falexwolf commented on Apr 17, 2019

    @falexwolf
    Member

    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.
    image
    Commit is here: scverse/anndata@97ad1e4

  3. tilofrei commented on Apr 17, 2019

    @tilofrei
    Author

    Thank you for the explanation and quick fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions