'How can I rename categories in pandas such that some categories are consolidated?

I have this lymph node AnnData set that has a wide variety of sometimes undescriptive and highly-specific cell types:

lymph_data.obs.cell_type = lymph_data.obs.cell_type.cat.rename_categories(
    {'B_mem': 'memory B cell', 
    'B_naive': 'naive B cell', 
    'T_CD4+_naive': 'naive CD4+ T cell', 
    'B_Cycling': 'cycling B cell', 
    'T_CD4+_TfH': 'TfH CD4+ T cell', 
    'T_CD8+_cytotoxic': 'cytotoxic CD8+ T cell', 
    'T_CD4+_TfH_GC': 'TfH CD4+ Germinal Center T cell', 
    'B_GC_LZ': 'Light Zone Germinal Center B cell', 
    'T_CD4+': 'CD 4+ T cell', 
    'T_Treg': 'Treg T cell',
    'B_GC_DZ': 'Dark Zone Germinal Center B cell',
    'T_CD8+_CD161+': 'CD8+ CD161+ T cell',
    'T_CD8+_naive': 'CD8+ naive T cell',
    'NK': 'natural killer cell',
    'B_activated,0': 'activated B cell 0',
    'B_plasma': 'plasma B cell',
    'T_TfR': 'TfR T cell',
    'B_activated,1': 'activated B cell 1',
    'NKT': 'natural killer T cell',
    'B_activated,2': 'activated B cell 2',
    'B_activated,3': 'activated B cell 3',
    'Endo': 'endothelial cell',
    'ILC': 'Innate lymphoid cell',
    'B_activated,4': 'activated B cell 4',
    'T_TIM3+': 'TIM3+ T cell',
    'Monocytes': 'monocyte',
    'DC_pDC': 'pDC',
    'B_IFN': 'Interferon B cell',
    'DC_cDC2': 'cDC2',
    'Macrophages_M1': 'M1 macrophage',
    'Macrophages_M2': 'M2 macrophage',
    'DC_cDC1': 'cDC1',
    'FDC': 'Follicular DC',
    'B_GC_prePB': 'prePB B cell',
    'DC_CCR7+': 'DC_CCR7+',
    'VSMC': 'VSMC',
    'Masth': 'mast cell'})

I would like to consolidate some of these cell types under the same category, for example, activated B cell 0-5. However, rename_categories requires the category names to remain unique, and using loc to subset and reassign values is inelegant and also gives me a similar issue when I try to call rename_categories. I feel like this would be easy with R's tidyverse, but I am new to pandas and I can't seem to find a good way to do this. Thank you!



Solution 1:[1]

lymph_data.obs.cell_type.replace(..)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CelineDion