Pandas Series: cat.rename_categories() function
Series-cat.rename_categories() function
The rename_categories() function is used to rename categories.
Syntax:
Series.cat.rename_categories(self, *args, **kwargs)
Parameters:
Name | Description | Type/Default Value | Required / Optional |
---|---|---|---|
new_categories |
|
list-like, dict-like or callable | Required |
inplace | Whether or not to rename the categories inplace or return a copy of this categorical with renamed categories. | bool, default False | Required |
Returns: cat : Categorical or None
Raises: ValueError
If new categories are list-like and do not have the same number of items than the current categories or do not validate as categories
Example:
Python-Pandas Code:
import numpy as np
import pandas as pd
c = pd.Categorical(['p', 'p', 'q'])
c.rename_categories([0, 1])
Output:
[0, 0, 1] Categories (2, int64): [0, 1]
Example - For dict-like new_categories, extra keys are ignored and categories not in the dictionary are passed through:
Python-Pandas Code:
import numpy as np
import pandas as pd
c = pd.Categorical(['p', 'p', 'q'])
c.rename_categories({'p': 'P', 'r': 'R'})
Output:
[P, P, q] Categories (2, object): [P, q]
Example - You may also provide a callable to create the new categories:
Python-Pandas Code:
import numpy as np
import pandas as pd
c = pd.Categorical(['p', 'p', 'q'])
c.rename_categories(lambda x: x.upper())
Output:
[P, P, Q] Categories (2, object): [P, Q]
Previous: Series-str.get_dummies() function
Next: Series-plot.area() function
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/pandas/series/series-cat-rename_categories.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics