Scanpy: How to merge sub-clusters or rename the categories with identical cluster names?

Created on 18 Nov 2019  路  7Comments  路  Source: theislab/scanpy

Hi,

To have a depth understanding, I wanted to set the resolution high for louvain clustering, but now I cannot merge subclusters. When I try to rename the categories with same cluster name, it gives an error about not having unique names. Yet, I could not find a functional merge_clusters function. Is there anyone having the same issue as me? I would appreciate any help. Thanks!

question

Most helpful comment

the clusters are simply annotations added in the adata.obs pandas dataframe. Thus, to merge the clusters you can create a new column containing your merged clusters. For example:

```PYTHON
old_to_new = dict(
old_cluster1='new_cluster1',
old_cluster2='new_cluster1',
old_cluster3='new_cluster2',
)
adata.obs['new_clusters'] = (
adata.obs['old_clusters']
.map(old_to_new)
.astype('category')
)
````

All 7 comments

the clusters are simply annotations added in the adata.obs pandas dataframe. Thus, to merge the clusters you can create a new column containing your merged clusters. For example:

```PYTHON
old_to_new = dict(
old_cluster1='new_cluster1',
old_cluster2='new_cluster1',
old_cluster3='new_cluster2',
)
adata.obs['new_clusters'] = (
adata.obs['old_clusters']
.map(old_to_new)
.astype('category')
)
````

For general help like this, please go to https://scanpy.discourse.group/

This is also what the issue template says. How could we have made the text more clear so that you鈥檇 have found your way there?

grafik

@fidelram, I like that! I had been struggling to come up with a concise way of doing this. I wonder if we can make that more concise. Here's one where the mapping can be defined inline, and you don't have to define relationships for the ones that stay the same:

adata.obs['new_clusters'] = (
    adata.obs["old_clusters"]
    .map(lambda x: {"a": "b"}.get(x, x))
    .astype("category")
)

@ivirshup I like that.

Here's a related question, if I want to make a labelling which includes a subset of clusters from a few different solutions, is there a concise way to write that? I.e. I want clusters 1,2, and 3 from clustering A, and clusters 4 and 5 from clustering B.

I think you will need two steps, one to get clusters 1,2, and 3 from clustering A and other for the rest

Can this method apply to Leiden clustering as well? I recapitulated the above code in my program, and my new cluster column returned only NaNs. What should the "old_cluster1" side of the structure look like when I am trying to make that dictionary?

Thanks

Was this page helpful?
0 / 5 - 0 ratings