pandas.CategoricalIndex.set_categories#
- CategoricalIndex.set_categories(new_categories, ordered=None, rename=False)[source]#
Set the categories to the specified new categories.
new_categoriescan include new categories (which will result in unused categories) or remove old categories (which results in values set toNaN). Ifrename=True, the categories will simply be renamed (less or more items than in old categories will result in values set toNaNor in unused categories respectively).This method can be used to perform more than one action of adding, removing, and reordering simultaneously and is therefore faster than performing the individual steps via the more specialised methods.
On the other hand this method does not check whether the old categories are included in the new categories on a reorder, which can result in surprising changes.
- Parameters:
- new_categoriesIndex-like
The categories in new order.
- orderedbool, default None
Whether or not the categorical is treated as an ordered categorical. If not given, do not change the ordered information.
- renamebool, default False
Whether or not the new_categories should be considered as a rename of the old categories or as reordered categories.
- Returns:
- CategoricalIndex
CategoricalIndex with the new categories.
- Raises:
- ValueError
If new_categories does not validate as categories
See also
CategoricalIndex.rename_categoriesRename categories.
CategoricalIndex.reorder_categoriesReorder categories.
CategoricalIndex.add_categoriesAdd new categories.
CategoricalIndex.remove_categoriesRemove the specified categories.
CategoricalIndex.remove_unused_categoriesRemove categories which are not used.
Examples
>>> ci = pd.CategoricalIndex( ... ["a", "b", "c", None], categories=["a", "b", "c"], ordered=True ... ) >>> ci CategoricalIndex(['a', 'b', 'c', nan], categories=['a', 'b', 'c'], ordered=True, dtype='category')
>>> ci.set_categories(["A", "b", "c"]) CategoricalIndex([nan, 'b', 'c', nan], categories=['A', 'b', 'c'], ordered=True, dtype='category') >>> ci.set_categories(["A", "b", "c"], rename=True) CategoricalIndex(['A', 'b', 'c', nan], categories=['A', 'b', 'c'], ordered=True, dtype='category')